計算字符串中有多少單詞,並輸出最長最短的單詞。(c++primer 9.39)

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
	string line1 = "We were her pride of 10 she named us:";
	string line2 = "Benjamin, Phoenix, the Prodigal";
	string line3 = "and perspicacious pacific Suzanne";
	string sentence = line1 + ' ' + line2 + ' ' + line3;
	string separators(" \t:,\v\r\n\f");//用作分隔符的字符。其中\t表示跳到下一個Tab位置。\r:回車。\n:換行。\f:換頁。\v:垂直製表符。
	string word;

	//sentence 中最長、最短單詞以及下一單詞的長度,單詞的數目。
	string::size_type maxlen, minlen, wordlen, count = 0;

	//存放最長及最短單詞的vector容器。
	vector<string> longestwords, shortestwords;

	//單詞的起始位置和結束位置。
	string::size_type startpos = 0,endpos = 0;

	//每次循環處理sentence中的一個單詞。
	while((startpos = sentence.find_first_not_of(separators, endpos)) != string::npos)
		{
		//找到下一個單詞的起始位置
		++count;

		//找下一個單詞的結束位置。
		endpos = sentence.find_first_of(separators, startpos);
		if(endpos == string::npos)
		{
			//找不到下一個出現分隔符的位置,即該單詞是最後一個單詞。
			wordlen = sentence.size() - startpos;
		}
		else 
		{
			//找到了下一個出現分隔符的位置
			wordlen = endpos - startpos;
			//cout << "wordlen: " << wordlen << endl;
        }
		word.assign(sentence.begin() + startpos, sentence.begin() + startpos + wordlen);//獲取單詞。

		cout <<"word: " << word << endl;
		//設置下次查找的起始位置
		if(count == 1)
		{
			//找到的是第一個單詞
			maxlen = minlen = wordlen;
			longestwords.push_back(word);
			shortestwords.push_back(word);
		}
		else
		{
			if(wordlen > maxlen)
			{
				//當前單詞比目前的最長單詞更長
				maxlen = wordlen;
				longestwords.clear();//清空存放最長單詞的容器
				longestwords.push_back(word);
			}
			else if(wordlen == maxlen)//當前單詞比目前的最長單詞等長
				longestwords.push_back(word);

			if(wordlen < minlen)//當前單詞比目前的最長單詞更短
			{
				minlen = wordlen;
				shortestwords.clear();//清空存放最長單詞的容器
				shortestwords.push_back(word);
			}
			else if (wordlen == minlen)//當前單詞比目前的最短單詞等長
				shortestwords.push_back(word);
		}
	}

	//輸出單詞數目
    cout << "word amount: " << count << endl;
	vector<string>::iterator iter,iter1;

	//輸出最長單詞
	cout << "longest word(s)" << endl;
	iter = longestwords.begin();
	while(iter != longestwords.end())
		cout << *iter++ << endl;

	//輸出最短單詞
	 cout << "shortest word(s):" << endl;
	 iter1 = shortestwords.begin();
	 while(iter1 != shortestwords.end())
		 cout << *iter1++ << endl;

	return 0;
}


輸入輸出結果;


發佈了29 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章