请使用while函数编写一个C语言程序,对字符串,除首、尾字符外,将其字符按ASCII编码数值降序排列
时间: 2024-03-12 20:45:22 浏览: 30
以下是一个使用while函数编写的C语言程序,可以对字符串进行字符按ASCII编码数值降序排列的操作:
```c
#include <stdio.h>
#include <string.h>
void sort(char str[]) {
int len = strlen(str);
int i = 1, j = len - 2;
while (i < j) {
if (str[i] < str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
i++;
j--;
}
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
sort(str);
printf("排序后的字符串为:%s\n", str);
return 0;
}
```
在这个程序中,我们首先使用了strlen函数获取了字符串的长度,然后设置了两个指针i和j,分别指向字符串的第二个字符和倒数第二个字符。接着,在while循环中,我们不断地比较并交换i和j指向的字符,直到i和j相遇为止。最后,我们输出排序后的字符串。
相关问题
请使用while函数将fun函数的内容补充完整,编写出一个C语言程序,对字符串,除首、尾字符外,将其字符按ASCII编码数值降序排列的操作:#include<stdio.h> #include<ctype.h> #include<string.h> #include<conio.h> void wwjt(); void fun(char *a,int len) { int i,j; char t; } main(){ char s[100]; int l; printf("输入字符串:"); gets(s); l=strlen(s); fun(s,l); printf("\n%s\n",s); wwjt(); }
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
void wwjt();
void fun(char *a, int len) {
int i, j;
char t;
i = 1;
j = len - 2; //除去首尾字符后的最后一个字符的下标
while (i < j) {
while (i < j && a[i] > a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
i++;
j--;
}
}
int main() {
char s[100];
int l;
printf("输入字符串:");
gets(s);
l = strlen(s);
fun(s, l);
printf("\n%s\n", s);
wwjt();
return 0;
}
void wwjt() {
printf("我爱计算机网络课程设计!\n");
}
不使用atoi函数的时候用c语言实现用户输入一个数字字符串,将其转为整型数据输出
可以使用循环和ASCII码进行转换。具体实现如下:
```c
#include <stdio.h>
int main() {
char str[20];
int i = 0, num = 0, sign = 1;
printf("请输入一个数字字符串:");
scanf("%s", str);
// 判断字符串是否为负数
if (str[0] == '-') {
sign = -1;
i = 1;
}
// 循环计算数字
while (str[i] != '\0') {
num = num * 10 + (str[i] - '0');
i++;
}
// 输出结果
printf("转换为整型数据为:%d\n", num * sign);
return 0;
}
```
运行结果:
```
请输入一个数字字符串:12345
转换为整型数据为:12345
请输入一个数字字符串:-6789
转换为整型数据为:-6789
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)