PAT1078-----switch与字符串

文本压缩有很多种方法,这里我们只考虑最简单的一种:把由相同字符组成的一个连续的片段用这个字符和片段中含有这个字符的个数来表示。例如 ccccc 就用 5c 来表示。如果字符没有重复,就原样输出。例如 aba 压缩后仍然是 aba

解压方法就是反过来,把形如 5c 这样的表示恢复为 ccccc

本题需要你根据压缩或解压的要求,对给定字符串进行处理。这里我们简单地假设原始字符串是完全由英文字母和空格组成的非空字符串。

输入格式:

输入第一行给出一个字符,如果是 C 就表示下面的字符串需要被压缩;如果是 D 就表示下面的字符串需要被解压。第二行给出需要被压缩或解压的不超过 1000 个字符的字符串,以回车结尾。题目保证字符重复个数在整型范围内,且输出文件不超过 1MB。

输出格式:

根据要求压缩或解压字符串,并在一行中输出结果。

输入样例 1:

C
TTTTThhiiiis isssss a   tesssst CAaaa as

输出样例 1:

5T2h4is i5s a3 te4st CA3a as

输入样例 2:

D
5T2h4is i5s a3 te4st CA3a as10Z

输出样例 2:

TTTTThhiiiis isssss a   tesssst CAaaa asZZZZZZZZZZ
 
 1 #include <stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include <math.h>
 5 #include<ctype.h> 
 6 #include <malloc.h>
 7 #include <iomanip>
 8 #include <stdlib.h>
 9 using namespace std;
10 
11 void compress()
12 {
13     char pervious=getchar(),current;   //前一个字符与后一个字符进行比较,不一样就输出 
14     int count=1;
15     while(current=getchar())           //到最后的换行符时的一个巧妙的办法 
16     {
17         if(pervious==current)
18         {
19             count++;
20         }else
21         {
22             if(count>1)
23             {
24                 cout<<count;
25             }
26             putchar(pervious);    //输出单个字符 
27             pervious=current;
28             count=1;
29         }
30         if(current=='\n')
31         {
32             break;
33         }
34     }
35 }
36 void depress()
37 {
38     char c;
39     int count=0;
40     while((c=getchar())!='\n')
41     {
42         if(isdigit(c))    //判断是否为0-9的字符 
43         {
44             count=count*10+c-'0';
45         }else
46         {
47             if(count==0)
48             {
49                 count=1;
50             }
51             for(int i=0;i<count;i++)
52             {
53                 cout<<c;
54             //    count=0;
55             }
56             count=0;           //注意count的条件放置位置 
57         }
58     }
59 }
60 int main()
61 {
62     char c;
63     cin>>c;
64     getchar();                  //用cin的话后面有一个\n是没有吸收的,你要吸收进去用getchar()
65     switch(c)
66     {
67         case 'C':
68                 compress();
69                 break;
70         case 'D':
71                 depress();
72                 break; 
73     }
74     return 0;
75 }

猜你喜欢

转载自www.cnblogs.com/BananaMan/p/11333234.html
今日推荐