string里strcmp怎么使用
时间: 2023-06-12 20:08:06 浏览: 42
strcmp是用于比较两个字符串的函数,可以用于判断两个字符串是否相同。它的函数原型如下:
```c++
int strcmp(const char* str1, const char* str2);
```
其中,str1和str2分别是要比较的两个字符串,函数返回值为0表示两个字符串相等,返回值大于0表示str1大于str2,返回值小于0表示str1小于str2。
例如,以下代码演示了如何使用strcmp函数进行字符串比较:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "hello";
char str2[] = "wrold";
int result = strcmp(str1, str2);
if(result == 0)
{
cout << "str1 is equal to str2" << endl;
}
else if(result > 0)
{
cout << "str1 is greater than str2" << endl;
}
else
{
cout << "str1 is less than str2" << endl;
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```
因为按照字典序,字母h比字母w小。