2016-06-07 80 views
-2

我一直在尝试从字符数组中获取字符串的一部分,并且对于我的生活,我无法获得任何在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; 
} 

我意识到张贴这可能会毁了我的名誉......但我无法找到解决办法....类似文章没有工作。

在此先感谢您的帮助:/

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

+3

你是一个'char'值进行比较,以一个'char'指针的元素。将''。“'改为''。''。 –

回答

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; 
} 
+0

谢谢MikeCAT,我今天学到了一些关于C的新东西,我从来没有听说过这个,一个很好的解释在这里:http://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c – con

+0

写“*”有效吗? ?? –

+0

@ machine_1是的。 – MikeCAT