我尝试在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++中已经有其他问题在问string〉array,但是我找不到任何满足我的条件的答案:不使用vector将字符串拆分为数组。
6条答案
按热度按时间lc8prwob1#
可以使用
std::stringstream
类将字符串转换为流(其构造函数以字符串作为参数)。一旦构建好,就可以使用>>
操作符(就像基于常规文件的流),它将从其中提取或 tokenize word:pvcm50d12#
jljoyd4f3#
brqmpdu14#
这里有一个建议:在字符串中使用两个索引,比如
start
和end
。start
指向要提取的下一个字符串的第一个字符,end
指向属于要提取的下一个字符串的最后一个字符之后的字符。start
从零开始,end
得到start
后面第一个字符的位置,然后取[start..end)
之间的字符串,并将其添加到数组中,一直添加到字符串的末尾。xwbd5t1u5#
输出:-
劈裂
在
空白
pw136qt26#
我为这个做了一个头,你可以用它把一个字符串拆分成一个字符串数组,用一个字符串作为拆分器,方法如下:
1.创建一个名为“WordSplitter.h”的文件,并将其与cpp文件的文件夹沿着保存。
1.复制粘贴到WordSplitter.h:
1.在cpp文件中:
输出: