简体   繁体   English

使用strcmp比较char数组上的字符

[英]compare a character on a char array by using strcmp

I would like to use strcmp to find a specific character on a char array. 我想使用strcmp在char数组上查找特定字符。 For example, I would like to detect the index number where . 例如,我想检测索引号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\n",i);
   }
}

however, it outputs "passing argument 1 of 'strcmp' makes pointer from integer without a cast " . 但是,它输出"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. 我注意到char数组是一个int,但是我无法弄清楚应该如何传递char索引。 Could you please tell me how I should have used the function? 您能告诉我该如何使用该功能吗?

Since it appears you want to scan the string backwards, you could do: 由于您似乎想向后扫描字符串,因此可以执行以下操作:

char host[100] = "hello.world";
size_t ii=0;

for(ii=strlen(host); ii--;){
   if(host[ii] ==  '.') { // compare characters, not strings
        printf("%zu\n", ii);
   }
}

This has the additional advantage of calling strlen() only once (the original code called it N*(N-1) times) 这还有另一个优点,即只调用一次strlen() (原始代码称它为N*(N-1)次)

This line: 这行:

if(strcmp(host[strlen(host)-i], ".")){

should look like this (ampersand added, to pass pointer to the char array's element): 应该看起来像这样(添加了&符,以将指针传递给char数组的元素):

if(strcmp(&host[strlen(host)-i], ".")){

It's true, though, as others already pointed out, that strcmp is not the best tool for the task. 但是,正如其他人已经指出的那样,确实如此, strcmp并不是执行任务的最佳工具。 You can use strchr or just compare the characters with '==' operator, if you prefer to roll your own loop. 如果您愿意滚动自己的循环,可以使用strchr或仅将字符与'=='运算符进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM