C语言 如何比较 2 个字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40605075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Compare 2 Character Arrays
提问by ThomasWest
How do I compare these two character arrays to make sure they are identical?
如何比较这两个字符数组以确保它们相同?
char test[10] = "idrinkcoke"
char test2[10] = "idrinknote"
I'm thinking of using for loop, but I read somewhere else that I couldnt do test[i] == test2[i]in C.
我正在考虑使用for loop,但我在其他地方读到了我test[i] == test2[i]在 C 中无法做到的。
I would really appreciate if someone could help this. Thank you.
如果有人可以帮助我,我将不胜感激。谢谢你。
回答by artm
but I read somewhere else that I couldnt do test[i] == test2[i] in C.
但我在其他地方读到我不能在 C 中做 test[i] == test2[i] 。
That would be really painful to compare character-by-character like that. As you want to compare two character arrays (strings) here, you should use strcmpinstead:
像这样逐个比较真的很痛苦。由于您想在这里比较两个字符数组(字符串),您应该strcmp改用:
if( strcmp(test, test2) == 0)
{
printf("equal");
}
Edit:
编辑:
There is no need to specify the size when you initialise the character arrays. This would be better:
char test[] = "idrinkcoke";char test2[] = "idrinknote";It'd also be better if you use
strncmp- which is safer in general (if a character array happens to be NOT NULL-terminated).if(strncmp(test, test2, sizeof(test)) == 0)
初始化字符数组时无需指定大小。这样会更好:
char test[] = "idrinkcoke";char test2[] = "idrinknote";如果您使用它也会更好
strncmp- 这通常更安全(如果字符数组碰巧以 NOT NULL 结尾)。if(strncmp(test, test2, sizeof(test)) == 0)
回答by Magisch
You can use the C library function strcmp
您可以使用 C 库函数 strcmp
Like this:
像这样:
if strcmp(test, test2) == 0
if strcmp(test, test2) == 0
From the documentation on strcmp:
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.
将 C 字符串 str1 与 C 字符串 str2 进行比较。
此函数开始比较每个字符串的第一个字符。如果它们彼此相等,则继续使用以下对,直到字符不同或到达终止空字符为止。
此函数执行字符的二进制比较。有关考虑特定于语言环境的规则的函数,请参阅 strcoll。
and on the return value:
并在返回值上:
returns 0 if the contents of both strings are equal
如果两个字符串的内容相等,则返回 0

