scu*_*zz0 4 c string if-statement function strcmp
在下面的代码中,我使用strcmp比较两个字符串,并将此比较作为if语句的条件.使用下面的代码,输出将是hello world,因为字符串"one"等于字符串"two".
#include <stdio.h>
#include <string.h>
char one[4] = "abc";
char two[4] = "abc";
int main() {
if (strcmp(one, two) == 0) {
printf("hello world\n");
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想更改程序,hello world如果两个字符串不同则打印它,所以我改变程序:
#include <stdio.h>
#include <string.h>
char one[4] = "abc";
char two[4] = "xyz";
int main() {
if (strcmp(one, two) == 1) {
printf("hello world\n");
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它不打印任何东西.
因为strcmp()在这种情况下将返回负整数.
所以改变这个:
if (strcmp(one, two) == 1) {
Run Code Online (Sandbox Code Playgroud)
对此:
if (strcmp(one, two) != 0) {
Run Code Online (Sandbox Code Playgroud)
考虑字符串不同的所有情况.
请注意,您可以通过读取引用或打印函数返回的内容来发现自己,如下所示:
printf("%d\n", strcmp(one, two));
// prints -23
Run Code Online (Sandbox Code Playgroud)