从键盘输入一个字符串,用冒泡法对该字符串中的字符由大到小进行排序,并输出结果。
时间: 2023-06-26 09:08:24 浏览: 73
以下是 Python 代码实现:
```python
s = input("请输入一个字符串:")
n = len(s)
arr = list(s)
for i in range(n-1):
for j in range(n-i-1):
if arr[j] < arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
result = "".join(arr)
print("排序后的字符串为:", result)
```
注:该代码只对单个字符进行排序,如果要对整个字符串按照字符顺序排序,则需要对字符串进行拆分后再进行排序。
相关问题
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/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)