strcmp怎么使用
时间: 2023-11-12 22:50:12 浏览: 32
strcmp是C语言中用于比较两个字符串的函数。它的原型如下:
```c
int strcmp(const char* str1, const char* str2);
```
该函数接受两个参数,分别是要比较的两个字符串str1和str2。strcmp会按照字典序逐个比较两个字符串的字符,直到找到不同的字符或者其中一个字符串结束为止。
如果str1小于str2,strcmp返回一个负整数;如果str1等于str2,返回0;如果str1大于str2,返回一个正整数。
下面是一个使用strcmp的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result == 0) {
printf("str1 is equal to str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```
相关问题
strcmp 使用方法
strcmp 是 C 语言中的一个字符串函数,用于比较两个字符串的大小。
其函数原型为:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1 和 s2 分别为要进行比较的两个字符串。
strcmp 函数的返回值为 int 类型,表示两个字符串的大小关系:
- 如果 s1 等于 s2,则返回 0;
- 如果 s1 大于 s2,则返回一个正整数;
- 如果 s1 小于 s2,则返回一个负整数。
下面是一个使用 strcmp 函数的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal\n");
} else if (strcmp(str1, str2) < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```
这是因为字符串 "hello" 在字典序上比字符串 "world" 要小。
strcmp使用注意事项
以下是strcmp函数的使用注意事项:
1. strncmp函数的前两个参数是需要进行比较的两个字符串,第三个是比较的字符个数,num是几就比较几个字符。
2. 源头字符串必须以’\0’结尾(若没有’\0’作为结束标志,strcpy就不知道什么时候停止拷贝)。
3. 源头字符串的’\0’会被拷贝到目标字符串中。
4. 目标字符串的空间必须足够大,否则会造成越界访问。
5. 目标字符串必须可修改(不能被const修饰)。