我不太精通C,但遇到了问题
- 逐个字符地遍历char *
- 正确比较单个字符和另一个字符
给定像“ abcda”这样的字符串,我想计算“ a”的数量并返回计数
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char** argv){
char* string_arg;
int counter = 0;
if(argc == 2){
for(string_arg = argv[1]; *string_arg != '\0'; string_arg++){
printf(string_arg);
printf("\n");
/*given abcda, this prints
abcda a
bcda b
cda but i want c
da d
a a */
if(strcmp(string_arg, "a") == 0){ //syntax + logical error
counter++;
}
}
printf(counter);
}
else{
printf("error");
}
return(0);
}
我也不应该使用strlen()
如何一次正确比较一个字符?
arg
isn't declared. It seems it should beargc
.printf(string_arg);
is dangerous becausestring_arg
is an user input, which can contain arbitrary string, which may include%
.strcmp()
if for comparing strings. You can use simply==
to compare characters.printf(counter);
is also wrong.}
at the end ofmain
function is missing.示例修复: