compare a character on a char array by using strcm

2019-02-21 00:23发布

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?

标签: c char strcmp
2条回答
何必那么认真
2楼-- · 2019-02-21 01:02

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)

查看更多
劫难
3楼-- · 2019-02-21 01:08

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.

查看更多
登录 后发表回答