C: 如何比较两个字符串? [英] C: How to compare two strings?
问题描述
这是重复的,我已将其标记为这样.请参阅[问题] 为什么是a"!= 一个"在 C 中?
This is a duplicate and I've flagged it as such. See [question] Why is "a" != "a" in C?
所以我试图根据结构中的字段打印出特定的消息.该字段包含字符串1".
So I'm trying to print out a specific message depending on a field within a struct. The field contains the string "1".
每当我运行 printf("%s", record.fields[2]);
时,输出都是 1
;我没有格式警告.
Whenever I run printf("%s", record.fields[2]);
the output is 1
; I've no format warnings.
但是,当我根据相应的字符串(在本例中为1")检查该字段时,检查失败:
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!");
}
推荐答案
你需要使用strncmp
比较字符串:
You need to use strncmp
to compare strings:
if (strncmp(record.fields[2], "1", 1) == 0) ...
您需要与零进行比较,因为当两个字符串相同时,strcmp
返回零.
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屋!