string将字符串根据空格分割
时间: 2023-09-10 12:05:04 浏览: 94
可以使用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将字符串按空格分割成几个字符串
可以使用字符串类中的split()函数将字符串按照空格分割成多个子字符串。
下面是一个示例代码:
```
String str = "Hello Arduino World";
String substrings[3];
int index = 0;
// 将字符串按照空格分割成多个子字符串
while (str.length() > 0) {
int spaceIndex = str.indexOf(' ');
if (spaceIndex == -1) {
substrings[index] = str;
str = "";
} else {
substrings[index] = str.substring(0, spaceIndex);
str = str.substring(spaceIndex+1);
}
index++;
}
// 输出分割后的子字符串
for (int i = 0; i < index; i++) {
Serial.println(substrings[i]);
}
```
在上面的代码中,我们首先定义了一个字符串str,然后声明了一个长度为3的字符串数组substrings,用于存储分割后的子字符串。接着使用while循环将字符串按照空格分割成多个子字符串,并将其存储到substrings数组中。最后使用for循环输出分割后的子字符串。
阅读全文
相关推荐
















