compare a character on a char array by using strcmp

元气小坏坏 提交于 2019-12-01 12:34:19

问题


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\n",i);
   }
}

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?


回答1:


This line:

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

should look like this (ampersand added, to pass pointer to the char array's element):

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. You can use strchr or just compare the characters with '==' operator, if you prefer to roll your own loop.




回答2:


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)



来源:https://stackoverflow.com/questions/17639578/compare-a-character-on-a-char-array-by-using-strcmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!