c语言中如何判断两个字符串相等

Python028

c语言中如何判断两个字符串相等,第1张

可以使用库函数strcmp判断,具体如下:

strcmp是C语言比较字符串的库函数,形式为int strcmp(char *a, char *b)

该函数会对a和b的每个字符,按照ascii码值比较,如果二者完全相同返回0;如果a的ascii码值先出现较大者,会返回1;否则返回-1。

所以,要判断字符串相等,可以使用。

扩展资料:

关于上述strcmp()函数比较字符串的例子

#include <stdio.h>

#include <string.h>

int main(void)

{

char str_1[] = "abc"

char str_2[] = "abc"

char str_3[] = "ABC"

if (strcmp(str_1, str_2) == 0)

printf("str_1 is equal to str_2. \n")

else

printf("str_1 is not equal to str_2. \n")

if (strcmp(str_1, str_3) == 0)

printf("str_1 is equal to str_3.\n")

else

printf("str_1 is not equal to str_3.\n")

return 0

}

参考资料来源:字符串-百度百科

不能这样比较。

首先,'有'不是ASCII码,它占两个字节。char b是ASCII码,占一个字节。

你的程序中,a是一个字符串,b是一个字符,两个类型不一样,不能用strcmp比较。

如果你想比较,可以这样:

#include <stdio.h>

#include <string.h>

int main()

{

char a,b

a='y'

b=getchar()

if(a == b)

   printf("两字都是 y \n")

else

   printf("第二个字不是 y\n")

return 0

}

C语言提供了几个标准库函数,可以比较两个字符串是否相同。以下是用strcmp()函数比较字符串的一个例子:\x0d\x0a \x0d\x0a#include \x0d\x0a#include \x0d\x0avoid main (void)\x0d\x0avoid main(void)\x0d\x0a{\x0d\x0achar* str_1 = "abc" char * str_2 = "abc" char* str_3 = "ABC" \x0d\x0aif (strcmp(str_1, str_2) == 0)\x0d\x0aprintf("str_1 is equal to str_2. \n")\x0d\x0aelse\x0d\x0aprintf("str_1 is not equal to str_2. \n")\x0d\x0aif (strcmp(str_1, str_3) == 0)\x0d\x0a printf("str_1 is equal to str_3.\n")\x0d\x0aelse\x0d\x0aprintf("str_1 is not equalto str_3.\n");\x0d\x0a}\x0d\x0a\x0d\x0a上例的打印输出如下所示: \x0d\x0astr_1 is equal to str_2. \x0d\x0astr_1 is not equal to str_3.\x0d\x0a \x0d\x0astrcmp()函数有两个参数,即要比较的两个字符串。strcmp()函数对两个字符串进行大小写敏感的(case-sensitiVe)和字典式的(lexicographic)比较,并返回下列值之一:\x0d\x0a----------------------------------------------------\x0d\x0a返 回 值 意 义\x0d\x0a----------------------------------------------------\x0d\x0a0 第一个字符串大于第二个字符串\x0d\x0a----------------------------------------------------\x0d\x0a在上例中,当比较str_1(即“abc”)和str_2(即“abc”)时,strcmp()函数的返回值为0。然而,当比较str_1(即"abc")和str_3(即"ABC")时,strcmp()函数返回一个大于0的值,因为按ASCII顺序字符串“ABC”小于“abc”。\x0d\x0astrcmp()函数有许多变体,它们的基本功能是相同的,都是比较两个字符串,但其它地方稍有差别。下表列出了C语言提供的与strcmp()函数类似的一些函数: \x0d\x0a-----------------------------------------------------------------\x0d\x0a函 数 名 作 用\x0d\x0a-----------------------------------------------------------------\x0d\x0astrcmp() 对两个字符串进行大小写敏感的比较\x0d\x0astrcmpi()对两个字符串进行大小写不敏感的比较\x0d\x0astricmp()同strcmpi()\x0d\x0astrncmp()对两个字符串的一部分进行大小写敏感的比较\x0d\x0astrnicmp() 对两个字符串的一部分进行大小写不敏感的比较\x0d\x0a-----------------------------------------------------------------\x0d\x0a在前面的例子中,如果用strcmpi()函数代替strcmp()函数,则程序将认为字符串“ABC”等于“abc”。