C:如何比较两个字符串? [英] C: How to compare two strings?
问题描述
编辑:这是一个重复的,我已经标记它是这样。参见[问题] 为什么" A" !=" A"用C?
所以我想打印出视场一个结构中的特定信息。该字段包含字符串1。
每当我跑的printf(%S,record.fields [2]);
输出 1
;我没有格式的警告。
然而,当我检查方面对相应的字符串(在这种情况下,1),它失败的检查:
如果(record.fields [2] ==1){
的printf(该字段为1!);
}
您需要使用的 STRNCMP
比较字符串:
如果(STRNCMP(record.fields [2],1,1)== 0)...
您需要比较为零,因为 STRCMP
返回零,当两个字符串是相同的。
不过,它看起来像你是不是比较字符串:相反,你正在寻找的字符串中特定的字符。在这种情况下,你需要使用一个字符常量,而不是字符串(单引号):
如果(record.fields [2] =='1')...
Edit: This is a duplicate and I've flagged it as such. See [question] Why is "a" != "a" in C?
So I'm trying to print out a specific message depending on a field within a struct. The field contains the string "1".
Whenever I run printf("%s", record.fields[2]);
the output is 1
; I've no format warnings.
However, when I check the field against the corresponding string (in this case, "1"), it fails the check:
if (record.fields[2] == "1") {
printf("The field is 1!");
}
You need to use strncmp
to compare strings:
if (strncmp(record.fields[2], "1", 1) == 0) ...
You need to compare to zero, because strcmp
returns zero when two strings are identical.
However, it looks like you are not comparing strings: rather, you are looking for a specific character inside the string. In this case, you need to use a character constant instead of a string literal (with single quotes):
if (record.fields[2] == '1') ...
这篇关于C:如何比较两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!