PTA刷题Basic篇——1043.输出PATest——Day(22)

题目描述

在这里插入图片描述
将给定字符串中的字母按照PATest这样的顺序排列,其他字母自动忽略,将最后的字符串输出即可。

题目分析

我们可以创建一个长度为6的计数数组,因为一共只有6个字母需要输出。再声明一个长度为6的word数组,通过count的索引准确输出对应字符。

word = {'P','A','T','e','s','t'};

遍历字符串中的字母,如果是P,A,T,e,s,t中的一个,就对应count位置+1.
P对应count[0],A对应count[1],T对应count[2],e对应count[3],s对应count[4],t对应count[5]。
最后我们遍历count数组,如果count[i]!=0,我们就将word[i]输出,直到所有count都为0停止输出。

代码

#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main(){    
	string str;    
	cin>>str;    
	int count[6] = {0};    
	char word[6] = {'P','A','T','e','s','t'};    
	for(int i = 0;i < str.length();i++)    
	{        
		if(int(str[i]) == 80)        
		{            
			count[0]++;        
		}        
		else if(int(str[i]) == 65)        
		{            
			count[1]++;        
		}        
		else if(int(str[i]) == 84)        
		{            
			count[2]++;        
		}        
		else if(int(str[i]) == 101)        
		{            
			count[3]++;        
		}        
		else if(int(str[i]) == 115)        
		{            
			count[4]++;        
		}        
		else if(int(str[i]) == 116)        
		{            
			count[5]++;        
		}    
	}    
	while(count[0] || count[1] || count[2] || count[3] || count[4] || count[5])    
	{        
		for(int i = 0;i < 6;i++)        
		{            
			if(count[i]!=0)            
			{                
				printf("%c",word[i]);                
				count[i]--;            
			}        
		}    
	}    
	return 0;
}

答题用时14min
Q43——finish√

原创文章 101 获赞 13 访问量 2327

猜你喜欢

转载自blog.csdn.net/weixin_44755413/article/details/105837050
今日推荐