【华为OJ】【字符排序】

这是一道关于字符串处理的编程题目,要求编写程序按照特定规则对输入字符串中的字符进行排序:英文字母按字母顺序排列且不区分大小写,相同字母保持原输入顺序,非字母字符位置不变。难度被标记为中级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

编写一个程序,将输入字符串中的字符按如下规则排序。 

规则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++;
		}
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值