通过使用STRCMP比较char阵列上的字符 [英] compare a character on a char array by using strcmp

查看:244
本文介绍了通过使用STRCMP比较char阵列上的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用的strcmp找一个char阵列上的特定字符。例如,我想检测的索引号,其中是文本。

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);
   }
}

然而,它输出过客的strcmp'的参数1时将整数指针,未作类型转换。我注意到,字符数组是一个int值,不过我无法弄清楚如何我应该已经通过了字符的索引。你能告诉我,我应该怎么使用了功能?

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?

推荐答案

这行:

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], ".")){

这是真的,但是,正如其他人已经指出的, STRCMP 不是任务的最佳工具。您可以使用和strchr 或只是字符'=='操作,如果你preFER推出自己的循环比较。

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.

这篇关于通过使用STRCMP比较char阵列上的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆