c++如何以空格切割字符串
可以使用stringstream类来实现以空格切割字符串的功能。具体步骤如下:
-
首先,将需要切割的字符串存入一个string类型的变量中。
-
接着,创建一个stringstream对象,将刚才存入的字符串作为参数传递给它的构造函数。
-
使用while循环和>>运算符从stringstream对象中读取每个以空格分隔的单词,并将其存入一个vector
容器中。 -
最后,将存储单词的vector
容器返回即可。
下面是一个示例代码:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
vector<string> splitStringBySpace(string str) {
vector<string> words;
stringstream ss(str);
string word;
while (ss >> word) {
words.push_back(word);
}
return words;
}
int main() {
string str = "This is a test string.";
vector<string> words = splitStringBySpace(str);
for (auto word : words) {
cout << word << endl;
}
return 0;
}
运行结果:
This
is
a
test
string.
原文地址: https://www.cveoy.top/t/topic/bgIr 著作权归作者所有。请勿转载和采集!