“C++学习笔记” 关于string:把一句话分解成单词,然后排序

        自己的学习笔记,如有错误,还请指正,谢谢。


初代版 :

        输入字符串直到“**”结束,对字符数组进行排序,再强行用了向量的函数。

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <string>

using namespace std;

int main()
{
	string arr[100];
	int i = 0;
	cout << "Please enter words until '**':"<< endl;
	do{
		cin >> arr[i];
		i++;
	} while (arr[i-1] != "**");

	cout << "You have enter "<< i - 1 << " words" << endl;
	cout << "Before sort:" << endl;
	for (int j = 0; j < i-1 ; j++)
	{
		cout << arr[j] << " ";
	}
	cout << endl;
	sort(arr, arr + i-1);

	vector<string> v;

	for (int j = 0; j < i-1; j++)
	{
		v.push_back(arr[j]);
	}
	cout << "After sort:" << endl;

	for (int j = 0; j < v.size(); j++) 
		cout << v[j] << ' '; 

	cout << endl;
	return 0;
}

改进版:

        挨个挨个的读入单词,然后把每个单词放到容器中,再排序。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
	vector<string> vectStrings;
	string word;
	char ch;
	do {
		cout << "Введите слово:";
		cin >> word;//读取到空格结束
		//getline(cin, word); 整个一行读取直到分隔符
		vectStrings.push_back(word);
		cout << "Продолжать ('y' или 'n'):";
		cin >> ch;
	} while (ch == 'y');

	sort(vectStrings.begin(), vectStrings.end());
	for (int k = 0; k < vectStrings.size(); k++)
		cout << vectStrings[k] << endl;

	return 0;
}

高阶版:

        输入一句英文含有空格,把句子中的单词提取出来,然后使用向量容器把它装进去,进行排序。

        用到了getline函数、for (auto x : str)函数、v.push_back( )函数、sort(v.begin(), v.end());

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

/*
void removeDupWord(string str)
{
	string word = "";
	for (auto x : str)
	{
		if (x == ' ')
		{
			cout << word << endl;
			word = "";
		}
		else {
			word = word + x;
		}
	}
	cout << word << endl;
}
*/


int main()
{
	vector<string> vectStrings;
	string str;

	getline(cin, str);

	string word = "";
	for (auto x : str)
	{
		if (x == ' ')
		{
			cout << word << endl;
			vectStrings.push_back(word);
			word = "";
		}
		else {
			word = word + x;
		}
	}
	cout << word << endl;

	vectStrings.push_back(word);
    cout<<endl;
	sort(vectStrings.begin(), vectStrings.end());
	for (int k = 0; k < vectStrings.size(); k++)
		cout << vectStrings[k] << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值