分享

用C++ STL实现的字符串分割

 mrjbydd 2012-06-21
#include <iostream>
02 #include <iterator>
03 #include <string>
04 #include <vector>
05   
06 using namespace std;
07   
08 vector<string> split(const string& s) {
09   
10     vector<string> ret;
11     typedef string::size_type string_size;
12     string_size i = 0;
13   
14     // invariant: we have processed characters [original value of i, i)
15     while (i != s.size()) {
16   
17         // ignore leading blanks
18         // invariant: chartacters in range [original i, current i) are all spaces
19         while (i !=s.size() && isspace(s[i]))
20             ++i;
21   
22         // find end of next word
23         string_size j = i;
24         // invariant: none of the characters in rang [original j, current j) is a space
25         while (j != s.size() && !isspace(s[j]))
26             ++j;
27   
28         // if we found some nonewithspace characters
29         if (i != j) {
30             // copy from s starting at i and taking j - i chars
31             ret.push_back(s.substr(i, j - i));
32             i = j;
33         }
34     }
35         return ret;
36 }
37   
38 int main() {
39   
40     string s;
41   
42     // read and split each line of input
43     while (getline(cin, s)) {
44         vector<string> v = split(s);
45   
46         // write eeach word in v
47         for (vector<string>::size_type i = 0; i != v.size(); ++i)
48             cout << v[i] << endl;
49     }
50   
51     system("PAUSE");
52     return 0;
53 }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多