我正在尝试使用 C++ 中的 vector 将一个由空格分隔的字符串插入到字符串数组中没有。例如:
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;
}
}
我希望输出是:
test
one
two
three.
我知道在 C++ 中已经有其他问题询问字符串 > 数组,但我找不到任何满足我的条件的答案:在不使用 vector 的情况下将字符串拆分为数组。
最佳答案
可以使用 std::stringstream
将字符串转换为流。类(它的构造函数接受一个字符串作为参数)。构建完成后,您可以在其上使用 >>
运算符(如常规基于文件的流),它将从中提取或 tokenize 单词:
#include <iostream>
#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;
}
}
关于c++ - 在不使用 vector 的情况下将字符串拆分为 C++ 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029324/