strcmp函数怎么用

admin 37 0

`strcmp`是C语言中的一个标准库函数,用于比较两个字符串,它的原型是`int strcmp(const char *s1, const char *s2);`,它比较两个字符串s1和s2。

这个函数会按字典顺序比较两个字符串,如果s1 < s2,它会返回一个负数,如果s1 == s2,它会返回0,如果s1 > s2,它会返回一个正数。

下面是一个例子来展示如何使用strcmp:

```c

#include

#include

int main() {

char str1[] = "Hello";

char str2[] = "World";

char str3[] = "Hello";

int result1 = strcmp(str1, str2);

int result2 = strcmp(str1, str3);

printf("Comparing '%s' and '%s': %d\n", str1, str2, result1);

printf("Comparing '%s' and '%s': %d\n", str1, str3, result2);

return 0;

}

在这个例子中,我们首先包含了stdio.h和string.h头文件。然后,我们定义了三个字符串:str1,str2和str3。我们使用strcmp函数比较这些字符串,并将结果存储在result1和result2变量中。最后,我们使用printf函数打印比较的结果。

输出将是:

vbnet

Comparing 'Hello' and 'World': -3

Comparing 'Hello' and 'Hello': 0

```

第一个输出是负数,因为"Hello"在字典顺序上位于"World"之前,第二个输出是0,因为"Hello"和"Hello"是相同的字符串。