string将字符串根据空格分割
时间: 2023-09-10 07:05:04 浏览: 47
可以使用C++ STL中的stringstream来实现字符串的分割,具体代码如下:
```c++
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string str = "hello world welcome to cpp";
stringstream ss(str); // 将字符串转换成stringstream类型
vector<string> result; // 定义一个vector来存储分割后的字符串
string temp;
while (ss >> temp) { // 当stringstream还有值时,不断取出单词
result.push_back(temp); // 将单词存入vector中
}
for (auto s : result) { // 输出vector中的每个单词
cout << s << endl;
}
return 0;
}
```
运行结果:
```
hello
world
welcome
to
cpp
```
相关问题
string将字符串根据特定字符串分割
你可以使用 `split()` 方法来将一个字符串根据特定的分隔符进行分割,例如:
```python
my_string = "hello world,how are you today"
split_string = my_string.split(",")
print(split_string)
```
输出结果为:
```
['hello world', 'how are you today']
```
在上面的例子中,我们使用逗号作为分隔符将字符串 `my_string` 分割成了两个子串 `'hello world'` 和 `'how are you today'`。你可以替换逗号为任何你想要的分隔符,比如空格、冒号、分号等等。
arduino将字符串通过空格分割为数组
以下是一个示例代码,可以将一个字符串通过空格分割为一个字符串数组:
```
String inputString = "Hello World Arduino";
String tokens[3]; // 定义一个大小为3的字符串数组
int i = 0;
while (inputString.length() > 0) {
int spaceIndex = inputString.indexOf(' '); // 查找空格的位置
if (spaceIndex == -1) { // 如果没有找到空格
tokens[i] = inputString; // 将剩余的字符串作为最后一个元素存入数组
break;
}
tokens[i] = inputString.substring(0, spaceIndex); // 截取空格之前的字符串存入数组
inputString = inputString.substring(spaceIndex + 1); // 更新输入字符串,去掉已经存入数组的部分
i++;
}
// 输出数组中的每个元素
for (int j = 0; j < 3; j++) {
Serial.println(tokens[j]);
}
```
在这个示例中,输入的字符串是"Hello World Arduino",我们定义了一个大小为3的字符串数组tokens。在while循环中,我们不断查找输入字符串中的空格,并将空格之前的字符串存入数组中。最后,我们输出数组中的每个元素。
这个示例代码还可以进一步改进,比如可以动态地分配字符串数组的大小,以适应不同长度的输入字符串。