C++: splitting a string into an array
我试图将一个由空格分隔的字符串插入到一个字符串数组中,而不使用C++中的向量。例如:
1 2 3 4 5 6 7 8 9 10 | using namespace std; int main() { string line ="test one two three."; string arr[4]; //codes here to put each word in string line into string array arr for(int i = 0; i < 4; i++) { cout << arr[i] << endl; } } |
我希望输出为:
1 2 3 4 | test one two three. |
我知道在C++中已经有很多问题问String >数组。我意识到这可能是一个重复的问题,但我找不到任何满足我条件的答案(不使用向量将字符串拆分为数组)。如果这是一个重复的问题,我提前道歉。
可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <sstream> using namespace std; int main(){ string line ="test one two three."; string arr[4]; int i = 0; stringstream ssin(line); while (ssin.good() && i < 4){ ssin >> arr[i]; ++i; } for(i = 0; i < 4; i++){ cout << arr[i] << endl; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> #include <sstream> #include <iterator> #include <string> using namespace std; template <size_t N> void splitString(string (&arr)[N], string str) { int n = 0; istringstream iss(str); for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n) arr[n] = *it; } int main() { string line ="test one two three."; string arr[4]; splitString(arr, line); for (int i = 0; i < 4; i++) cout << arr[i] << endl; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #define MAXSPACE 25 string line = "test one two three."; string arr[MAXSPACE]; string search =""; int spacePos; int currPos = 0; int k = 0; int prevPos = 0; do { spacePos = line.find(search,currPos); if(spacePos >= 0) { currPos = spacePos; arr[k] = line.substr(prevPos, currPos - prevPos); currPos++; prevPos = currPos; k++; } }while( spacePos >= 0); arr[k] = line.substr(prevPos,line.length()); for(int i = 0; i < k; i++) { cout << arr[i] << endl; } |
琐碎的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const vector<string> explode(const string& s, const char& c) { string buff{""}; vector<string> v; for(auto n:s) { if(n != c) buff+=n; else if(n == c && buff !="") { v.push_back(buff); buff =""; } } if(buff !="") v.push_back(buff); return v; } |
跟随链路
这里有一个建议:在字符串中使用两个索引,比如