简体   繁体   中英

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. 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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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