C++ 字符串按空格分隔成 vector<char> - 详细代码示例
C++ 字符串按空格分隔成 vector
可以使用 stringstream 来实现字符串按照空格分隔成 vector
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = 'hello world';
vector<char> vec;
stringstream ss(str);
string word;
while (ss >> word) {
for (int i = 0; i < word.size(); i++) {
vec.push_back(word[i]);
}
vec.push_back(' '); // 加入空格
}
vec.pop_back(); // 去掉最后一个空格
for (char c : vec) {
cout << c;
}
cout << endl;
return 0;
}
输出结果为:
h e l l o w o r l d
代码说明:
- 使用
stringstream将字符串str转换为一个可读写流对象ss。 - 使用
while循环从ss中读取单词,并将其存储到word中。 - 遍历每个单词的字符,并将其添加到
vec中。 - 在每个单词后添加一个空格,以便将单词之间分隔开。
- 最后移除最后一个空格。
- 使用循环遍历
vec中的字符,并输出到控制台。
其他方法:
除了 stringstream 之外,还可以使用 std::getline 函数来读取字符串,并使用 std::isspace 函数来判断字符是否是空格。
总结:
本文介绍了如何使用 C++ 中的 stringstream 将一个字符串按照空格分隔成 vector<char>,并提供了完整代码示例和输出结果。希望对大家有所帮助。
原文地址: https://www.cveoy.top/t/topic/nWZ1 著作权归作者所有。请勿转载和采集!