我的程序中有strcmp的问题.
我试图按照它们的长度比较两个字符串,所以我使用strcmp(),但是当我在if语句中比较它们时它不能正常工作.
strcmp不比较字符串的长度吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char a[30],b[30],c[30];
strcpy(a,"computer");
strcpy(c,"science");
strcpy(b,a);
puts(a);
puts(c);
puts(b);
if(strcmp(a,b)==0)
printf("a=b\n");
if(strcmp(a,c)<0)
printf("a<c\n");
if(strcmp(a,c)>0)
printf("a>c");
strcat(a,c);
puts(a);
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
strcmp按字典顺序比较字符串(对于由同一寄存器中的字母组成的字符串,它与按字母顺序进行比较相同).因此,"computer"较少,而不是更大"science",因为它是按字母顺序提前的.
如果您想比较两个字符串的长度而不是比较字符串本身,您应该使用strlen:
if(strlen(a) == strlen(b))
printf("a=b\n");
if(strlen(a) < strlen(c))
printf("a is shorter than c\n");
if(strlen(a) > strlen(c))
printf("a is longer than c");
Run Code Online (Sandbox Code Playgroud)