使用 strcmp 比较 char 数组中的字符 [英] compare a character on a char array by using strcmp
问题描述
我想使用 strcmp 在 char 数组中查找特定字符.例如,我想检测 .
在文本上的索引号.
I would like to use strcmp to find a specific character on a char array. For example, I would like to detect the index number where .
is on the text.
char host[100] = "hello.world";
size_t i=0;
for(i=0;i<strlen(host);i++){
if(strcmp(host[strlen(host)-i], ".")){
printf("%d
",i);
}
}
然而,它输出 传递 'strcmp' 的参数 1 使指针来自整数而不进行强制转换"
.我注意到 char 数组是一个 int,但我无法弄清楚我应该如何传递 char 索引.你能告诉我应该如何使用这个功能吗?
however, it outputs "passing argument 1 of 'strcmp' makes pointer from integer without a cast "
. I notice that char array is a int, but I could not figure out how I should have passed the char index. Could you please tell me how I should have used the function?
推荐答案
这一行:
if(strcmp(host[strlen(host)-i], ".")){
应该看起来像这样(添加和号,以将指针传递给 char 数组的元素):
should look like this (ampersand added, to pass pointer to the char array's element):
if(strcmp(&host[strlen(host)-i], ".")){
确实,正如其他人已经指出的那样,strcmp
并不是完成这项任务的最佳工具.您可以使用 strchr
或仅将字符与 '==' 运算符进行比较,如果您喜欢滚动自己的循环.
It's true, though, as others already pointed out, that strcmp
is not the best tool for the task. You can use strchr
or just compare the characters with '==' operator, if you prefer to roll your own loop.
这篇关于使用 strcmp 比较 char 数组中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!