c++ 字符串空格分割字符串
时间: 2023-12-02 11:38:16 浏览: 167
可以使用 stringstream 和 getline 函数来实现字符串的空格分割。具体实现如下:
```c++
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s = "hello world, how are you?";
stringstream ss(s);
string token;
vector<string> tokens;
while (getline(ss, token, ' ')) {
tokens.push_back(token);
}
for (auto t : tokens) {
cout << t << endl;
}
return 0;
}
```
上述代码中,我们首先定义了一个字符串 s,然后使用 stringstream 将其转换为一个流对象 ss。接着,我们定义了一个字符串变量 token 和一个字符串向量 tokens,然后使用 getline 函数从 ss 中逐个读取以空格为分隔符的字符串,并将其存储到 tokens 中。最后,我们遍历 tokens 并输出其中的每个字符串。
相关问题
C++字符串空格遇到分隔怎么实现?
在C++中,如果你想要处理字符串并根据空格将其分割成多个单词,你可以使用`std::string`的内置功能,特别是`find()`函数来查找空格的位置,然后结合`substr()`函数来提取每个子串。以下是一个简单的示例:
```cpp
#include <iostream>
#include <sstream>
std::vector<std::string> splitString(const std::string &str) {
std::istringstream iss(str);
std::vector<std::string> tokens;
std::string token;
while (iss >> token) {
if (!token.empty()) { // 如果不是空格,则添加到结果中
tokens.push_back(token);
}
}
return tokens;
}
int main() {
std::string input = "Hello World, This is a test string.";
std::vector<std::string> words = splitString(input);
for (const auto& word : words) {
std::cout << word << std::endl;
}
return 0;
}
```
这个`splitString`函数会返回一个包含所有非空格单词的`std::vector`。如果想按照空格进行分隔,可以直接使用逗号`,`作为分隔符,只需稍微修改`while`循环条件即可。
c++ string空格分割字符串
可以使用 stringstream 和 getline 函数来实现空格分割字符串,示例代码如下:
```c++
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s = "hello world";
stringstream ss(s);
vector<string> tokens;
string token;
while (getline(ss, token, ' ')) {
tokens.push_back(token);
}
for (const auto& t : tokens) {
cout << t << endl;
}
return 0;
}
```
输出结果为:
```
hello
world
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)