从键盘输入一个字符串,用冒泡法对该字符串中的字符由大到小进行排序,并输出结果。
时间: 2024-02-19 16:58:00 浏览: 22
好的,这个问题我可以回答。以下是 C++ 代码实现:
```c++
#include <iostream>
#include <cstring>
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 << "请输入一个字符串:" << endl;
cin >> str;
bubbleSort(str);
cout << "排序后的字符串为:" << str << endl;
return 0;
}
```
冒泡排序的基本思想是从数组的第一个元素开始,依次比较相邻的两个元素,如果前一个元素比后一个元素大,则交换这两个元素的位置,一轮比较下来,最大的元素就被交换到了数组的最后面。重复上述过程,每次比较的元素个数减少1,直到只剩下一个元素为止。对于本题,我们可以将字符串中的字符看作是一个数组,按照上述思路进行排序即可。
相关问题
c语言从键盘输入一个字符串,用冒泡法对该字符串中的字符由大到小进行排序,并输出结果。
下面是一个使用冒泡排序对输入的字符串进行字符由大到小排序的 C 语言程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int len, i, j;
char temp;
printf("请输入一个字符串:");
gets(str); // 从键盘输入字符串
len = strlen(str);
// 冒泡排序
for(i = 0; i < len - 1; i++) {
for(j = 0; j < len - 1 - i; j++) {
if(str[j] < str[j+1]) {
temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
}
printf("排序后的字符串为:%s", str);
return 0;
}
```
例如,如果输入字符串为 "hello world",则程序输出的结果为 "wroollleeihd "。
从键盘输入一个字符串,用冒泡法对该字符串中的字符由大到小进行排序,并输出结果。C语言
好的,以下是 C 语言的代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, j, n;
printf("请输入一个字符串:");
scanf("%s", str);
n = strlen(str);
// 冒泡排序
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (str[j] < str[j + 1]) {
char temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
}
printf("排序后的字符串为:%s\n", str);
return 0;
}
```
代码中,首先从键盘读入一个字符串,然后通过 strlen() 函数获取字符串的长度。接着使用冒泡排序对字符串中的字符进行排序,最后输出排序后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)