单词排序(字符串排序)

描述

输入一行单词序列,相邻单词之间由1个或多个空格间隔,请按照字典序输出这些单词,要求重复的单词只输出一次。(区分大小写)

格式

输入格式

一行单词序列,最少1个单词,最多100个单词,每个单词长度不超过50,单词之间用至少1个空格间隔。数据不含除字母、空格外的其他字符。

输出格式

按字典序输出这些单词,重复的单词只输出一次。

样例

输入样例

She  wants  to go to Peking University to study  Chinese

输出样例

Chinese
Peking
She
University
go
study
to
wants

思路:从小到大排序

注意:输入数据后,因为cin>>s[n]的存在,跳不出循环,所以添加判断是否为换行符来结束循环,

#include <iostream>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;

int main ()
{
	string s[105];
	int n=0, tmp;
	while ((cin >> s[n])) {
		tmp = 0;
		for (int i=0; i<n; i++) 
			if (s[i].compare(s[n]) == 0)
				tmp = 1;
		if (tmp == 0)	
			n++;
		if (getchar() == '\n') //跳出去
			break;
	}
	sort(s, s+n);
	for (int i=0; i<n; i++)
		cout << s[i] << endl;
	return 0;
}
发布了89 篇原创文章 · 获赞 77 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/wodemaoheise/article/details/104623739
今日推荐