将char数组元素与字符串文字进行比较

时间:2016-06-07 14:30:40

标签: c arrays string

我一直在尝试从char数组中获取字符串的一部分,而对于我的生活,我无法获得我在StackOverflow上找到的任何示例: Compare string literal vs char array 我已经在互联网上寻找解决方案,我尝试过混合指针,strcmp,strncmp,我能想到的一切。

我看不出如何让它发挥作用:

#include <stdio.h>

int main(void) {
 const char S[] = "0.9";
 if (S[1] == ".") {
    puts("got it");
 }
 return 0;
}

我意识到这可能会破坏我的声誉......但我找不到解决方案......类似的文章并没有起作用。

提前感谢您的帮助:/

编辑:我不知道要使用的正确搜索字词;这就是为什么我没找到指定的原件。

1 个答案:

答案 0 :(得分:4)

"."是一个字符串文字。你想要的应该是一个角色常数'.'

试试这个:

#include <stdio.h>
#include <string.h>

int main(void) {
 const char S[] = "0.9";
 if (S[1] == '.') {
    puts("got it");
 }
 return 0;
}

替代(但看起来更糟)方式:访问字符串文字的元素

#include <stdio.h>
#include <string.h>

int main(void) {
 const char S[] = "0.9";
 if (S[1] == "."[0]) {
    puts("got it");
 }
 return 0;
}
相关问题