请用C语言编写函数fun, 对长度为7个字符的字符串, 除首、尾字符外,将其余5个字符按ASCII码降序排列。 例如,原来的字符串为 CEAedca,排序后输出为 CedcEAa 。
时间: 2024-04-29 20:25:22 浏览: 105
可以的,以下是C语言编写的函数fun:
```
#include <stdio.h>
#include <string.h>
void fun(char* s) {
int len = strlen(s);
char temp;
for(int i = 1; i < len - 1; i++) {
for(int j = i + 1; j < len - 1; j++) {
if(s[i] < s[j]) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
printf("%s\n", s);
}
```
该函数的作用是对长度为7个字符的字符串进行排序,除首、尾字符外,将其余5个字符按ASCII码降序排列。例如,原来的字符串为 CEAedca,排序后输出为 CedcEAa。
相关问题
请编写C语言函数fun, 对长度为7个字符的字符串, 除首、尾字符外,将其余5个字符按ASCII码降序排列。 例如,原来的字符串为 CEAedca,排序后输出为 CedcEAa 。
好的,以下是实现该功能的C语言函数fun的代码:
```c
#include <stdio.h>
#include <string.h>
void fun(char str[]) {
int len = strlen(str);
int i, j;
char temp;
// 冒泡排序
for (i = 1; i < len - 1; i++) {
for (j = len - 2; j >= i; j--) {
if (str[j] < str[j-1]) {
temp = str[j];
str[j] = str[j-1];
str[j-1] = temp;
}
}
}
// 输出结果
for (i = 1; i < len - 1; i++) {
printf("%c", str[i]);
}
printf("%c%c\n", str[0], str[len-1]);
}
```
函数中先使用冒泡排序算法对除首尾字符外的字符进行排序,然后再按照要求输出结果。注意在输出结果时需要先输出除首尾字符外的字符,再输出首尾字符。
希望可以帮到您!
编写函数fun(),对长度为7个字符的字符串,除首、尾字符外,将其余5个字符按照降序排列。例如,原来的字符串为CEAedca,排序后输出为CedcEAa。用c语言
以下是实现fun()函数的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void fun(char str[])
{
int len = strlen(str);
char temp;
for (int i = 1; i < len - 1; i++) {
for (int j = i + 1; j < len - 1; j++) {
if (str[j] > str[i]) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
int main()
{
char str[] = "CEAedca";
fun(str);
printf("%s\n", str);
return 0;
}
```
在函数中,我们使用了两层循环,对除首尾字符外的子串进行降序排序。排序完成后,原字符串就被修改为排好序的字符串。最后在主函数中,我们输出排好序后的字符串。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.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)
![](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)