题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include <stdio.h>
#include<string.h>
#include<malloc.h>
#include<ctype.h> //大小写转换函数
char* Judge(char* str) {
//1、英文字母从 A 到 Z 排列,不区分大小写。
//2、同一个英文字母的大小写同时存在时,按照输入顺序排列。
//3、非英文字母的其它字符保持原来的位置。这个保持不动就好
//思路把大小写统一在看是否排序 tolower(ch)把大写字母换成小写,把字母挑出来先排序,排好序在放进去其他的不动
int len = strlen(str);
int i, j, index = 0;
char temp[1001] = ""; //用于存放字母
for (i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'A' && str[i] <= 'Z' ) || (str[i] >= 'a' &&
str[i] <= 'z')) //字母
temp[index++] = str[i]; //把是字母的字符放入temp数组
}
//对字母数组排序用冒泡排序,注意还得把大小写统一
for (i = 0; i < index; i++) {
for (j = 0; j < index - i - 1; j++) {
if (tolower(temp[j]) > tolower(temp[j + 1])) {
char t = temp[j];
temp[j] = temp[j + 1];
temp[j + 1] = t;
}
}
}
//将排好的数组再放入
for (i = 0, j = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'A' && str[i] <= 'Z' ) || (str[i] >= 'a' && str[i] <= 'z'))
str[i] = temp[j++]; //把排好的放入,其他的不变
}
return str;
}
int main() {
char* str = (char*)malloc(1000 * sizeof(char));
gets(str);
Judge(str);
puts(str);
free(str);
}
tolower函数的使用说明:
1、包含头文件
#include <ctype.h>
2、函数声明
int tolower(int c);
3、功能说明
把大写字母转换为小写字母,如果参数c不是大写字母就不转换,您可能会问:tolower函数的参数和返回值是整数,不是字符,在C语言中,字符就是整数。
参数c为待转换的字符。
返回值为转换后的结果。
同理C库函数 int toupper(int c)转换给定的字母为大写。
C语言刷题 文章被收录于专栏
自己从头开始刷的C语言

查看13道真题和解析