C++字符串的排序
时间: 2023-08-06 19:26:36 浏览: 53
可以使用 `std::sort()` 函数对字符串进行排序,代码示例如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello world";
sort(str.begin(), str.end());
cout << str << endl;
return 0;
}
```
输出结果为:` dehllloorw`。
如果需要按照字典序进行排序,可以使用 `std::less<string>()` 作为 `sort()` 函数的第三个参数,代码示例如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello world";
sort(str.begin(), str.end(), less<string>());
cout << str << endl;
return 0;
}
```
输出结果为:` dlhlooorw`。
相关问题
字符串的排序C++
可以使用C++中自带的sort函数来对字符串数组进行排序。
示例代码如下:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string arr[] = {"orange", "apple", "banana", "grape", "pear"};
int n = sizeof(arr) / sizeof(arr[0]);
// 对字符串数组进行排序
sort(arr, arr + n);
// 输出排序后的结果
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:
```
apple banana grape orange pear
```
这里使用了C++中的string类型,string类型也可以使用sort函数进行排序。
c++字符串从小到大排序
可以使用 STL 中的 `sort` 函数对字符串进行从小到大排序。例如:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string s = "cba";
sort(s.begin(), s.end());
cout << s << endl; // 输出 abc
return 0;
}
```
在这个例子中,我们使用 `sort` 函数对字符串 `s` 进行排序,函数的参数是字符串的起始地址和结束地址,即 `s.begin()` 和 `s.end()`。排序后,字符串 `s` 的内容变为从小到大排列的字符序列。