compare a character on a char array by using strcmp

守給你的承諾、 提交于 2019-12-01 14:23:46

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.

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)

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