我正在尝试迭代字符串的单词.
可以假设该字符串由用空格分隔的单词组成.
请注意,我对C字符串函数或那种字符操作/访问不感兴趣.另外,请在答案中优先考虑优雅而不是效率.
我现在最好的解决方案是:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s = "Somewhere down the road";
istringstream iss(s);
do
{
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
} while (iss);
}
Run Code Online (Sandbox Code Playgroud)
有没有更优雅的方式来做到这一点?
我试图插入一个由空格分隔的字符串到一个字符串数组,而不使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
test
one
two
three.
Run Code Online (Sandbox Code Playgroud)
我知道在C++中已经有很多问题要求字符串>数组.我意识到这可能是一个重复的问题,但我找不到任何满足我条件的答案(将字符串拆分为数组而不使用向量).如果这是一个重复的问题,我会提前道歉.
我正在阅读来自诸如"5 8 12 45 8 13 7"之类文件的输入行.
我可以将这些整数直接放入数组中,还是必须先将它们放入字符串中?
如果最初使用字符串是必须的,我该如何将这个整数字符串转换为数组?
输入:"5 8 12 45 8 13 7"=>进入一个数组:{5,8,12,45,8,13,7}