问题描述
我正在尝试使用C ++中的vector将用空格分隔的字符串插入到字符串 without 中.例如:
I am trying to insert a string separated by spaces into an array of strings without using vector in C++. For example:
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 ++中还有其他问题要问字符串>数组,但是找不到满足我条件的答案:不使用向量将字符串拆分成数组.
I know there are already other questions asking string > array in C++, but I could not find any answer satisfying my conditions: splitting a string into an array WITHOUT using vector.
推荐答案
可以使用 std::stringstream
类(其构造函数将字符串作为参数).构建完成后,您可以在其上使用>>
运算符(就像在基于常规文件的流上一样),该运算符将从中提取或 tokenize 单词:
It is possible to turn the string into a stream by using the std::stringstream
class (its constructor takes a string as parameter). Once it's built, you can use the >>
operator on it (like on regular file based streams), which will extract, or tokenize word from it:
#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 ++中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!