题目描述:
编写一个程序,将输入字符串中的字符按如下规则排序。
规则1:英文字母从A到Z排列,不区分大小写。
如,输入:Type 输出:epTy
规则2:同一个英文字母的大小写同时存在时,按照输入顺序排列。
如,输入:BabA 输出:aABb
规则3:非英文字母的其它字符保持原来的位置。
如,输入:By?e 输出:Be?y
本题考查知识点:字符串
本题难度:中级
/*****************************************************************************
Description : 对输入字符串进行排序
Input Param : str 待排序的字符串
Output Param : str 排序后的字符串
Return Value : 成功返回0,失败返回-1(比如,str为NULL)
*****************************************************************************/
/* 思路:1.判断是否是英文字母;2.遍历整个字符串,如果是英文字母,比较大小,进行排序;
* 3.如何实现规则1?不能单纯的比较ascii码,进行转换,对大写字母让其+32,进行比较
* 4.如何实现规则2?遍历字符串,找其大小写;
* 5.如何实现规则3?非英文字母保持不动
* 6.最关键的是设计一个存储结构
* 将大小写字母分开存储
*/
#include <string.h>
#include <stdlib.h>
int sort_string(char* str)
{
int len = strlen(str);
int cnt_alpha = 0;
int cnt_p = 0;
int cnt_index = 0;
int cnt_alpha_out = 0;
int cnt_p_out = 0;
int cnt_index_out = 0;
char *p_alpha = (char *)malloc(len*(sizeof(char *)));//存储字母
char *p = (char *)malloc(len*(sizeof(char *)));//存储特殊字符
int *p_index = (int *)malloc(len*(sizeof(int *)));//存储特殊字符下标
for(int i = 0;i < len;i++)
{
if(str[i] >= 'a'&&str[i] <= 'z'||str[i] >= 'A'&&str[i] <= 'Z')
{
//对其存储字母
p_alpha[cnt_alpha] = str[i];
cnt_alpha++;
}else{//存储特殊字母,需要记录其下标
p[cnt_p] = str[i];
p_index[cnt_index] = i;
cnt_p++;
cnt_index++;
}
}
//重要的一步,清楚指针的屯屯屯
p_alpha[cnt_alpha] = '\0';
p[cnt_p] = '\0';
p_index[cnt_index] = '\0';
for(int i = 0;i < cnt_alpha-1;i++)
{
for(int j = 0;j < cnt_alpha-i-1;j++)
{
int temp = 0,tempj = 0,tempj_1 = 0;
if(p_alpha[j] >= 'a')//如果是小写字母转换为大写字母进行计算
{
tempj = p_alpha[j] -32;//str[j] = str[j] -32;这样做是错的
}else{
tempj = p_alpha[j];
}
if(p_alpha[j+1] >= 'a')
{
tempj_1 = p_alpha[j+1] -32;
}else{
tempj_1 = p_alpha[j+1];
}
if(tempj > tempj_1)
{
temp = p_alpha[j+1];
p_alpha[j+1] = p_alpha[j];
p_alpha[j] = temp;
}
}
}
for(int i = 0;i < len;i++)
{
if(p_index[cnt_index_out] == i)//error:if(p_index[cnt_index_out] = i)
{
str[i] = p[cnt_p_out];
cnt_p_out++;
cnt_index_out++;
}else{
str[i] = p_alpha[cnt_alpha_out];
cnt_alpha_out++;
}
}