分割string字符串
时间: 2023-08-07 11:10:52 浏览: 62
你可以使用split()函数来分割字符串,该函数将根据指定的分隔符将字符串分割为一个列表。例如:
```python
string = "hello world"
words = string.split(" ")
print(words) # ['hello', 'world']
```
在上面的例子中,我们使用空格作为分隔符来分割字符串。你还可以使用其他分隔符,比如逗号、分号等。
```python
string = "apple,banana,orange"
fruits = string.split(",")
print(fruits) # ['apple', 'banana', 'orange']
```
注意:split()函数返回的结果是一个列表,你可以使用列表索引来访问单个元素。
相关问题
C++分割string字符串
在 C++ 中,可以使用 `std::string` 类型和 `std::stringstream` 类型来分割字符串。
方法一:使用 `std::stringstream`
```cpp
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "hello world how are you";
std::stringstream ss(str);
std::vector<std::string> tokens;
std::string token;
while (std::getline(ss, token, ' ')) {
tokens.push_back(token);
}
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
```
输出:
```
hello
world
how
are
you
```
方法二:使用 `std::string` 的 `find` 函数和 `substr` 函数
```cpp
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string str = "hello world how are you";
std::vector<std::string> tokens;
size_t pos = 0;
std::string token;
while ((pos = str.find(' ')) != std::string::npos) {
token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + 1);
}
tokens.push_back(str);
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
```
输出:
```
hello
world
how
are
you
```
Android 以“,”分割String字符串 以String[]显示
可以使用Java中的split()方法将一个字符串按照指定字符分割成字符串数组,然后再输出每个字符串。具体代码如下:
```java
String str = "Android,以,逗号,分割,String,字符串";
String[] strArray = str.split(",");
for (String s : strArray) {
System.out.println(s);
}
```
输出结果为:
```
Android
以
逗号
分割
String
字符串
```