What's the best way to compare two strings for equality in C? [duplicate]

时间秒杀一切 提交于 2019-12-31 04:55:08

问题


I have got two strings (string literals in that case), say

char *name        = "Fotis";
char *second_name = "Fotis";

and I have two ways to compare them, which are both giving me an accurate result. The first one is with the equality operator (==), likewise:

if (name == second_name)
    printf ("Great success!\n");

and the second one is through the strcmp function available in string.h:

if (strcmp (name, second_name) == 0)
    printf ("Great success!\n");

My question is: Which one of the two is the most {efficient | idiomatic} way to compare two strings in C? Is there another, more idiomatic way?


回答1:


The second way with strcmp is correct, the first way using == is incorrect because it's only comparing the value of pointers, not the contents of the strings.

The two strings that you compare happen to be both string literals, they may, and may not have the same pointer value by the standard.




回答2:


The natural way would be to use strcmp since it's more accurate.




回答3:


Your first method using == is comparing the pointers, so it will only return true if the two are exactly the same char array, meaning they point to the same piece of memory. The other method using strcmp is the way you would do this, because it is comparing the actual content of the strings. So it can return true even if the two strings are in different locations in memory.

The reason your first method is appearing to work correctly is because the two variables are pointing to the same string literal, so they basically point to the same location in memory when they're the same string, and different locations when they're different strings. If you used malloc to allocate memory for those strings, and set their contents, then they would point to different locations in memory, so your first method would return false and the second would return true for the same string of text.




回答4:


if (name == second_name)
    printf ("Great success!\n");

Watch out: you're comparing pointers equality with this one, not the strings' texts.



来源:https://stackoverflow.com/questions/21610282/whats-the-best-way-to-compare-two-strings-for-equality-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!