帮忙写一个c++代码 内容是实现五个字符串要求他们从小到大顺序排序用string方法
时间: 2023-04-03 09:01:57 浏览: 71
好的,以下是实现五个字符串从小到大排序的 C 代码,使用了 string 方法:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[5][20], temp[20];
int i, j;
printf("请输入五个字符串:\n");
for (i = ; i < 5; i++) {
scanf("%s", str[i]);
}
for (i = ; i < 4; i++) {
for (j = i + 1; j < 5; j++) {
if (strcmp(str[i], str[j]) > ) {
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
printf("排序后的字符串为:\n");
for (i = ; i < 5; i++) {
printf("%s\n", str[i]);
}
return ;
}
```
相关问题
C++写一个函数,用起泡法对输入的10个字符串按从小到大顺序排列
好的,这里是一个用起泡法对输入的10个字符串按从小到大顺序排列的C++函数示例:
```c++
#include <iostream>
#include <string>
using namespace std;
void bubble_sort_strings(string str_list[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (str_list[j] > str_list[j+1]) {
swap(str_list[j], str_list[j+1]);
}
}
}
}
int main() {
string str_list[10] = {"apple", "banana", "orange", "pear", "grape", "kiwi", "watermelon", "mango", "pineapple", "peach"};
int n = 10;
bubble_sort_strings(str_list, n);
for (int i = 0; i < n; i++) {
cout << str_list[i] << " ";
}
cout << endl;
return 0;
}
```
这个函数接收一个包含10个字符串的数组和数组的大小作为输入,并使用嵌套的循环来进行起泡排序。在内部循环中,我们比较相邻的两个字符串,如果它们的顺序不正确,就交换它们。最终,我们输出已排序的字符串数组。
请注意,这个函数是对字符串进行排序的,而不是对数字进行排序。如果你需要对数字进行排序,需要先将数字转换为字符串。
从键盘接收一个字符串,然后将字符串中的字符按照从小到大的顺序输出。用C++
以下是一种可以实现上述功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// 定义比较函数,用于qsort函数中排序
int cmp(const void *a, const void *b) {
return *(char*)a - *(char*)b;
}
int main() {
char str[1000];
printf("请输入一个字符串:\n");
scanf("%s", str);
// 对字符串中的字符进行排序
int len = strlen(str);
qsort(str, len, sizeof(char), cmp);
// 输出排序后的字符串
printf("排序后的字符串为:\n%s\n", str);
return 0;
}
```
以上代码通过使用标准库函数 `qsort` 对输入的字符串进行排序,然后将结果输出。在排序时,我们定义了一个比较函数 `cmp`,用于指定排序规则。由于题目中要求按照字母从小到大的顺序排序,所以我们可以直接使用 `cmp` 函数对字符进行比较。