排序文本中的單詞

#include <iostream>
#include <iomanip>
#include <string>
using std::cout;
using std::endl;
using std::string;

string* sort(string* strings,size_t count)
{
  bool swapped{false};
  while(true)
  {
    for(size_t i{};i<count-1;i++)
     {
       if(strings[i]>strings[i+1])
         {
           swapped=true;
           strings[i].swap(strings[i+1]);
           }
         }
       if(!swapped)
         break;
       swapped=false;
       }
     return strings;
 }

int main()
{
  const size_t maxwords{100};
  string words[maxwords];
  string separators{" \".,:;!?()\n"};
  size_t nwords{};
  size_t maxwidth{};
  cout<<"enter some text on as many lines as you wish."
   <<endl<<"terminate the input with an asterisk:"<<endl;
  std::getline(std::cin,text,'*');
  size_t start{},end{},offset{};
  while(true)
  {
     start=text.find_first_not_of(separators,offset);
  if(string::npos==start)
    break;
  offset=start+1;
  end=text.find_first_of(separators,offset);
  if(string::npos==end)
  {
    offset=end;
    end=text.length();
  }
   else
     offset=end+1;
   words[nwords]=text.substr(start,end-start);
   if(maxwidth<words[nwords].length())
    maxwidth=words[nwords].length();
   if(++nwords==maxwords)
   {
     cout<<"maximum number of words reached."
        <<"processing what we have"<<endl;
      break;
    }
    if(string::npos==offset)
      break;
  }
   sort(words,nwords);
  cout<<endl<<"in ascending sequence,the words in the text are:"<<endl;
  size_t count{1};
  char initial{words[0][0]};
  for(size_t i{};i<nwords;i++)
  {
    if(i<nwords-1&&words[i]==words[i+1])
    {
      ++count;
      continue;
    }
    if(initial!=words[i][0])
    {
      initial=words[i][0];
      cout<<endl;
     }
     cout<<std::setiosflags(std::ios::left)
    <<std::setw(maxwidth+2)<<words[[i];
   cout<<std::resetiosflags(std::ios::right)   <<std::setw(5)<<count;
   count=1;
  }
   cout<<endl;
   return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章