c++中字符串cmp函数
时间: 2024-04-19 11:18:56 浏览: 7
C++中的字符串比较函数是strcmp,它可以比较两个字符串的大小。该函数的原型如下:
```c++
int strcmp(const char* str1, const char* str2);
```
其中,str1和str2是要比较的两个字符串,函数返回值为0表示两个字符串相等,返回值大于0表示str1大于str2,返回值小于0表示str1小于str2。
例如,以下代码比较了两个字符串s1和s2的大小:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[] = "hello";
char s2[] = "world";
int result = strcmp(s1, s2);
if (result == 0)
cout << "s1 equals s2" << endl;
else if (result > 0)
cout << "s1 is greater than s2" << endl;
else
cout << "s1 is less than s2" << endl; return 0;
}
```
输出结果为:
```
s1 is less than s2
```
相关问题
C++两个字符串比较大小
C++中可以使用字符串比较函数`string::compare()`对两个字符串进行比较大小。示例代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "hello";
string str2 = "world";
// 使用string::compare()函数比较大小
int cmp = str1.compare(str2);
if (cmp == 0) {
cout << "str1和str2相等" << endl;
} else if (cmp > 0) {
cout << "str1大于str2" << endl;
} else {
cout << "str1小于str2" << endl;
}
return 0;
}
```
输出结果为:str1小于str2。
在代码中,我们首先定义了两个字符串str1和str2,并初始化为"hello"和"world"。然后使用string::compare()函数对两个字符串进行比较大小,并将比较结果赋值给变量cmp。最后根据cmp的值判断两个字符串的大小关系,并输出对应的结果。如果cmp等于0,则表示两个字符串相等;如果cmp大于0,则表示str1大于str2;如果cmp小于0,则表示str1小于str2。
sort函数字符串排序
sort函数可以用于对字符串进行排序。在C++中,字符串可以用字符数组或者string类型表示。当使用字符数组表示字符串时,需要使用strcmp函数来进行字符串的比较。在sort函数中,可以自定义比较函数,用于指定排序的方式。比如,如果要按照字符串长度从小到大排序,可以定义一个比较函数,比较两个字符串的长度,然后在sort函数中传入该比较函数即可。下面是一个示例代码:
```
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool cmp(string a, string b) {
return a.length() < b.length();
}
int main() {
string arr[] = {"apple", "banana", "orange", "pear"};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, cmp);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
该代码使用了string类型表示字符串,并定义了一个比较函数cmp,用于按照字符串长度从小到大排序。在main函数中,先定义了一个字符串数组arr,然后使用sort函数对其进行排序,并输出排序后的结果。