10815 Andy’s First Dictionary

題目原文

題目說明
輸入一段文章,輸出每一單字,並按字典序排列。

思路
一個單字一個單字去讀,若遇到像 andy's 這種詞,須將其切割為 andy 和 s 兩個單字,
讀完丟入 set (會自動依字典序排列),再利用迭代器輸出即可。

  1. #include<iostream>
  2. #include<cctype>
  3. #include<cstring>
  4. #include<sstream>
  5. #include<set>
  6. using namespace std;
  7.  
  8. set<string> dict;
  9.  
  10. int main()
  11. {
  12. string input;
  13. while(cin >> input)
  14. {
  15. for(int i = 0; i < input.length(); i++)
  16. {
  17. if(isalpha(input[i]))
  18. input[i] = tolower(input[i]);
  19. else
  20. input[i] = ' '; // 非字母轉成空白字元 (ex. andy's 變 andy s)
  21. }
  22. stringstream ss; // 拿來切割 (ex. andy s 變兩個字串)
  23. ss << input;
  24. string output;
  25. while(ss >> output)
  26. dict.insert(output); // 會自動由小到大排
  27. }
  28. set<string>::iterator it;
  29. for(it = dict.begin(); it != dict.end(); it++)
  30. cout << *it << endl;
  31. return 0;
  32. }

留言

這個網誌中的熱門文章

機率筆記 (1)

離散數學筆記 — vertex cut

機率筆記 (4) — 隨機變數