7-8 字符串排序--string类的使用 代码
时间: 2024-03-10 08:49:55 浏览: 41
以下是一个简单的字符串排序程序,使用了 string 类:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
string s[n];
for (int i = 0; i < n; i++) {
cin >> s[i];
}
sort(s, s + n);
for (int i = 0; i < n; i++) {
cout << s[i] << endl;
}
return 0;
}
```
程序首先读入字符串的数量 n,然后使用一个 string 数组来存储这些字符串。
然后调用 sort 函数来对字符串数组进行排序,最后输出排序后的结果。
相关问题
字符串排序--string类的使用 用Java写代码
以下是一个使用 Java 写的字符串排序程序,同样使用了 String 类:
```java
import java.util.Arrays;
import java.util.Scanner;
public class StringSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] s = new String[n];
for (int i = 0; i < n; i++) {
s[i] = sc.next();
}
Arrays.sort(s);
for (int i = 0; i < n; i++) {
System.out.println(s[i]);
}
}
}
```
程序首先读入字符串的数量 n,然后使用一个 String 数组来存储这些字符串。
然后调用 Arrays.sort 函数来对字符串数组进行排序,最后输出排序后的结果。
pta 7-143字符串排序
这是一道基础的字符串排序题目,可以使用STL中的sort函数来实现。
具体解法如下:
1. 首先读入字符串个数n和n个字符串,存储在一个vector<string>中。
2. 使用sort函数对vector中的字符串进行排序,排序规则为按照字符串长度从小到大排序,如果长度相等则按照字典序从小到大排序。
3. 最后按照顺序输出已排序的字符串即可。
代码示例:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) {
if (a.length() != b.length()) {
return a.length() < b.length();
} else {
return a < b;
}
}
int main() {
int n;
cin >> n;
vector<string> strs(n);
for (int i = 0; i < n; i++) {
cin >> strs[i];
}
sort(strs.begin(), strs.end(), cmp);
for (int i = 0; i < n; i++) {
cout << strs[i] << endl;
}
return 0;
}
```