C语言 如何在C中比较指向字符串的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3663668/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:24:19 来源:igfitidea点击:
How to compare pointer to strings in C
提问by Rn2dy
how to compare two strings in C? Help me, I am beginner@@
如何比较C中的两个字符串?帮帮我,我是初学者@@
char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
回答by Daniel Vassallo
You may want to use strcmp:
您可能想要使用strcmp:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int v;
const char *str1 = "hello";
const char *str2 = "world";
v = strcmp(str1, str2);
if (v < 0)
printf("'%s' is less than '%s'.\n", str1, str2);
else if (v == 0)
printf("'%s' equals '%s'.\n", str1, str2);
else if (v > 0)
printf("'%s' is greater than '%s'.\n", str1, str2);
return 0;
}
Result:
结果:
'hello' is less than 'world'.
回答by AndersK
if ( strcmp( str1, str2 ) == 0 )
same

