【PAT 】——【字符串处理+scanf(),gets(),getchar()读取输入】1078 字符串压缩与解压

目录

一【题目描述】

二【题目样例】

三【解题思路】

四【代码实现】


一【题目描述】

 

二【题目样例】

 

三【解题思路】

输入时注意:

①:一定要用getchar()读取换行符,再用gets()读取字符串

        因为读入scanf()读入C或D时,不读取换行符,而又输入换行符。

        若不用getchar()读取  ,直接用gets(),gets()遇到换行符直接结束

有以下两个情况:

①:压缩,借助 while()
②:第二种情况就是要解压,只要扫描到数字就记录下来,然后按照个数打印字母即可,但是需要注意,数字的个数可能超过1位,所以可能有两位数甚至三位数的可能,
其中有两个坑点:

 

四【代码实现】

#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
using namespace std;
int main(){
	char x,str[1001];
	scanf("%c",&x);
	getchar();//吸收换行符 
	gets(str);
	if(x=='C'){//压缩
			int i=0;
			for(int i=0;i<strlen(str);i++){
				int count=1;
				while(str[i]==str[i+1]){
					count++;
					i++;	
				}
				if(count>1) printf("%d",count);
				printf("%c",str[i]); 
				i++; 
			
	  	    } 
		
	}
	if(x=='D'){//解压
		int i=0;
		for(int i=0;i<strlen(str);i++){
			int count=0;
			while(str[i]>='0'&&str[i]<='9'){
				count=count*10+str[i]-'0';
				i++;
			}
			if(count==0) printf("%c",str[i]);
			else{
				while(count--){
				printf("%c",str[i]);	
			}
			}
			
			i++;
		} //
			
	} 
}

	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值