【发布时间】:2015-06-10 03:46:15
【问题描述】:
所以我可能以错误的方式攻击它;我正在学习一点 Javascript,并编写了一个程序,该程序将查找包含在另一个字符串中的字符串并将匹配项存储在一个数组中(抱歉,如果这没有太大意义,请参阅我的 C 程序应该有帮助)。我试图将我的程序翻译成 C,但它不起作用;我认为我的问题是数据类型:
int main () {
char text[58];
strcpy(text, "I am James, James the Great, a pretty cool guy named James");
char store[16];
char name[6] = "James";
for (int i = 0; i <= 16; i++) {
if (text[i] == 'J') {
for (int k = i; k < i + 6; k++) {
store[k] = text[i];
}
}
}
int a = sizeof(store) / sizeof(store[0]);
for (int b = 0; b < a; b++) {
/* This should print out the values stored in the store array */
printf("%d", store[b]);
}
return 0;
}
我的预期结果是这样的:
JamesJamesJames
相反,我得到:
10000747474747474-6374747474
所以我假设它正在做我告诉它做的事情,只是没有将字母作为字母存储到数组中,这有点令人困惑。有没有更好的方法来做到这一点?
这是我试图翻译的 javascript 代码:
var text = "I am James, James the Great, a pretty cool guy named James";
var myName = "James";
var hits =[];
for (i = 0; i < text.length; i++) {
if (text[i] === "J") {
for (var j = i; j < i + myName.length ; j++) {
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else{
console.log(hits);
}
【问题讨论】:
-
0)
"%d"-->"%c" -
单纯使用系统函数strstr()会不会有问题?