编写程序计算 sentence 中有多少个单词,并指出其中最长和最短的单词。如果有多个最长或最短的单词,则将它们全部输出。
/*已知有如下 string 對象:?
9.39:
?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;?
編寫程序計算 sentence 中有多少個單詞,并指出其中
最長和最短的單詞。如果有多個最長或最短的單詞,則
將它們全部輸出。*/
int main(void)
{
?? ?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;
?? ??? ?cout<<sentence.c_str()<<endl;
?? ??? ?int num = 0, count = 0; string strs; vector<char> str; vector<string>strss;
?? ??? ?while (num< sentence.size())
?? ??? ?{
?? ??? ??? ?if (isalnum(sentence.c_str()[num]))
?? ??? ??? ?str.push_back(sentence.c_str()[num]);
?? ??? ??? ?if (isalnum((sentence.c_str()[num++])) && !isalnum((sentence.c_str()[num])))//非字母做運算
?? ??? ??? ?{
?? ??? ??? ??? ?
?? ??? ??? ??? ?count++;
?? ??? ??? ??? ?
?? ??? ??? ?}
?? ??? ?}
?? ??? ?strs.assign(str.begin(), str.end());
?? ??? ?string::size_type pos = 0, pos1 = 0; vector<char>str1; string strs1; vector<string>strss1;
?? ??? ?while ((pos = sentence.find_first_not_of(strs, pos)) != string::npos)
?? ??? ?{
?? ??? ??? ?for (pos1; pos1 < pos; pos1++)
?? ??? ??? ??? ?if (isalnum(sentence[pos1]))
?? ??? ??? ??? ??? ?str1.push_back(sentence[pos1]);//計算字串做單詞
?? ??? ??? ?strs1.assign(str1.begin(),str1.end());//復制字符串到string對象
?? ??? ??? ?strss1.push_back(strs1);//入棧string對象到string容器
?? ??? ??? ?str1.erase(str1.begin(), str1.end());//清除前面多余字符串
?? ??? ??? ?pos1 = pos;//定位到下個單詞
?? ??? ??? ?++pos;//定位到下個坐標?? ?
?? ??? ?}
?? ??? ?vector<int> value;
?? ??? ?for (int i = 0; i < strss1.size(); i++)
?? ??? ?{
?? ??? ??? ?value.push_back(strss1[i].size());
?? ??? ?}
?? ??? ?int max = value[0], min = value[0];
?? ??? ?for (int i = 1; i < value.size(); i++)
?? ??? ?{
?? ??? ??? ?if (max < value[i])
?? ??? ??? ??? ?max = value[i];
?? ??? ??? ?if (min > value[i]&&value[i]!=0)
?? ??? ??? ??? ?min = value[i];
?? ??? ?}
?? ??? ?
?? ??? ?//for (size_t i = 0; i != value.size(); i++)
?? ??? ?//{
?? ??? ?//?? ?cout << strss1[i];
?? ??? ??? ?//cout << value[i] << endl;
?? ??? ?//}
?? ?
?? ??? ?cout << "最短單詞有:" << endl;
?? ??? ?for (int i = 0; i < value.size(); i++)
?? ??? ?{
?? ??? ??? ?
?? ??? ??? ?if (strss1[i].size() == min)
?? ??? ??? ?{
?? ??? ??? ??? ?cout << strss1[i]<<'\t';
?? ??? ??? ?}
?? ??? ?}
?? ??? ?cout << endl<<"最長單詞有:" << endl;
?? ??? ?for (int i = 0; i < value.size(); i++)
?? ??? ?{
?? ??? ??? ?if (strss1[i].size() == max)
?? ??? ??? ?{
?? ??? ??? ??? ?cout << strss1[i] << '\t';
?? ??? ??? ?}
?? ??? ?}
?? ??? ?cout << endl<<"sentence擁有" << count << "單詞";
?? ?return 0;
}
?
總結
以上是生活随笔為你收集整理的编写程序计算 sentence 中有多少个单词,并指出其中最长和最短的单词。如果有多个最长或最短的单词,则将它们全部输出。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编写程序处理一个 string 类型的
- 下一篇: 雉离爱吃的东西是什么(鸡形目雉科动物)