"This is a statement"ios
使用 C++ 將這個字符串分割成四個子字符串: "This", "is", "a", "statement"?函數
超級簡略版code
cpp#include <iostream> using std::cout; #include <iterator> using std::istream_iterator; using std::ostream_iterator; #include <string> using std::string; #include <sstream> using std::istringstream; #include <algorithm> using std::copy; int main() { string str("This is a statement"); istringstream iss(str), end; copy(istream_iterator<string>(iss), istream_iterator<string>(end), ostream_iterator<string>(cout, "\n")); return 0; }
這個技巧不足爲道,C++ Primer 5th 中 10.4.2. iostream Iterators 裏有介紹。ip
工程實用版字符串
上面的方法雖然簡潔,可是僅可以按空格分隔,在實際工程中,顯然是沒太大用處的,抽出一個 split
函數仍是頗有必要的。get
cpp#include <iostream> using std::cout; using std::getline; #include <iterator> using std::ostream_iterator; #include <string> using std::string; #include <sstream> using std::istringstream; #include <vector> using std::vector; #include <algorithm> using std::copy; vector<string> &split(const string &str, char delim, vector<string> &elems, bool skip_empty = true) { istringstream iss(str); for (string item; getline(iss, item, delim); ) if (skip_empty && item.empty()) continue; else elems.push_back(item); return elems; } int main() { string str("Windows,Linux,,MacOS,"); vector<string> result; split(str, ',', result); copy(result.begin(), result.end(), ostream_iterator<string>(cout, "\n")); return 0; }
這樣咱們不只能夠用別的字符來作分隔,還能夠選擇跳過空白字符串,如我故意在 Linux 和 MacOS 之間放了兩個相鄰的 ,,
,若不作處理和判斷的話,就會多分割出一個空白字符來。string
繼續改進版it
上面這樣,還有一個限制未解決,即若是我想按多種字符來分隔呢?如按照 ,
,|
以及空格,來分割字符串。io
能夠利用 find_first_of
來實現。stream
cpp#include <string> using std::string; #include <vector> using std::vector; #include <iostream> vector<string> &split( const string &str, const string &delimiters, vector<string> &elems, bool skip_empty = true ) { string::size_type pos, prev = 0; while ( ( pos = str.find_first_of(delimiters, prev) ) != string::npos ) { if ( pos > prev ) { if ( skip_empty && 1 == pos - prev ) break; elems.emplace_back( str, prev, pos - prev ); } prev = pos + 1; } if ( prev < str.size() ) elems.emplace_back( str, prev, str.size() - prev ); return elems; } int main() { string str( "Windows,Linux||MacOS All" ); vector<string> result; for ( const auto &s : split( str, ",| ", result ) ) std::cout << s << " "; std::cout << std::endl; }
這個版本基本知足大部分工程上的須要了。