用C++,并且使用气泡法将字符串按ASCII码值从小到大排列
时间: 2024-02-22 22:56:31 浏览: 61
好的,可以使用冒泡排序的方法来实现字符串按ASCII码值从小到大排列。具体实现方法如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
void bubbleSort(string& str) {
int n = str.length();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (str[j] > str[j + 1]) {
swap(str[j], str[j + 1]);
}
}
}
}
int main() {
string str;
cout << "请输入字符串: ";
getline(cin, str); // 使用 getline 函数读入整行字符串
bubbleSort(str);
cout << "按ASCII码值从小到大排序后的字符串为: " << str << endl;
return 0;
}
```
上述代码中,`bubbleSort` 函数使用冒泡排序的方法,将字符串中的字符按ASCII码值从小到大排列。主函数中,使用 `getline` 函数读入整行字符串,并调用 `bubbleSort` 函数对其进行排序输出。
相关问题
用c++写用起泡法将字符串按ASCII码值从小到大排列
以下是用冒泡排序法将字符串按ASCII码值从小到大排列的C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
void bubbleSort(string& str) {
int len = str.length();
for (int i = 0; i < len - 1; ++i) {
for (int j = 0; j < len - i - 1; ++j) {
if (str[j] > str[j + 1]) {
swap(str[j], str[j + 1]);
}
}
}
}
int main() {
string str;
cout << "Please enter a string: ";
getline(cin, str);
bubbleSort(str);
cout << "Sorted string: " << str << endl;
return 0;
}
```
在上述代码中,我们首先定义一个名为 `bubbleSort` 的函数,该函数接受一个字符串参数并使用冒泡排序法将其按ASCII码值从小到大排列。然后在 `main` 函数中,我们从用户输入中获取一个字符串,调用 `bubbleSort` 函数对其进行排序,并输出排序后的结果。
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个字符串的数组和数组的大小作为输入,并使用嵌套的循环来进行起泡排序。在内部循环中,我们比较相邻的两个字符串,如果它们的顺序不正确,就交换它们。最终,我们输出已排序的字符串数组。
请注意,这个函数是对字符串进行排序的,而不是对数字进行排序。如果你需要对数字进行排序,需要先将数字转换为字符串。