[关闭]
@guochy2012 2014-03-04T07:29:16.000000Z 字数 1517 阅读 1378

字符串逆置

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stdlib.h>
  5. #include <assert.h>
  6. int count_word(const std::string&);
  7. void swap(char&, char&);
  8. void reverse_string(std::string &s, std::size_t begin, std::size_t end);
  9. std::string& reverse_word(std::string &s);
  10. void print(const std::string &s);
  11. int main(int argc, char** argv)
  12. {
  13. std::string s =
  14. "I have a book named Advanced Programming of UNIX Environment";
  15. reverse_word(s);
  16. print(s);
  17. return 0;
  18. }
  19. void print(const std::string &s)
  20. {
  21. std::cout << s << std::endl;
  22. }
  23. void swap(char &a, char &b)
  24. {
  25. char _tmp = a;
  26. a = b;
  27. b = _tmp;
  28. }
  29. void reverse_string(std::string &s, std::size_t begin, std::size_t end)
  30. {
  31. assert(begin <= end);
  32. while (begin < end)
  33. {
  34. swap(s[begin++], s[end--]);
  35. }
  36. }
  37. std::string& reverse_word(std::string &s)
  38. {
  39. bool flag = false;
  40. std::size_t first = 0;
  41. for (std::size_t ix = 0; ix != s.length(); ++ix)
  42. {
  43. if (s[ix] == ' ' && flag)
  44. {
  45. flag = false;
  46. reverse_string(s, first, ix - 1);
  47. }
  48. else if (!flag && isalpha(s[ix]))
  49. {
  50. flag = true;
  51. first = ix;
  52. }
  53. else if (ix == s.length() - 1 && flag)
  54. {
  55. flag = false;
  56. reverse_string(s, first, ix);
  57. }
  58. }
  59. reverse_string(s, 0, s.length() - 1);
  60. return s;
  61. }
  62. int count_word(const std::string &s)
  63. {
  64. bool flag = false;
  65. std::size_t cnt = 0;
  66. std::vector<std::string> vec;
  67. std::size_t first = 0;
  68. for (std::size_t ix = 0; ix != s.length(); ++ix)
  69. {
  70. if (s[ix] == ' ' && flag)
  71. {
  72. flag = false;
  73. std::string tmp_s = s.substr(first, ix - first);
  74. vec.push_back(tmp_s);
  75. cnt++;
  76. }
  77. else if (!flag && isalnum(s[ix]))
  78. {
  79. flag = true;
  80. first = ix;
  81. }
  82. else if (ix == s.length() - 1 && flag)
  83. {
  84. std::string tmp_s = s.substr(first, ix - first + 1);
  85. vec.push_back(tmp_s);
  86. cnt++;
  87. }
  88. }
  89. std::vector<std::string>::const_iterator iter = vec.begin();
  90. for (; iter != vec.end(); iter++)
  91. {
  92. std::cout << *iter << std::endl;
  93. }
  94. return cnt;
  95. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注