字符串集合转换为long集合
时间: 2023-08-08 22:05:03 浏览: 87
可以将字符串集合中的每个字符串转换为long类型,然后将它们添加到一个新的long类型的集合中。具体代码如下:
```java
Set<String> stringSet = new HashSet<>();
// 添加一些字符串到 stringSet 中
Set<Long> longSet = new HashSet<>();
for (String str : stringSet) {
longSet.add(Long.parseLong(str));
}
```
这样就可以将字符串集合转换为long集合了。需要注意的是,如果字符串中包含非数字字符,则会抛出NumberFormatException异常,因此需要在转换之前进行一些检查或异常处理。
相关问题
string字符串转list<long>集合
在将string字符串转换为list<long>集合过程中,需要使用stringstream对象进行初始化并逐个读取字符串中的每个long类型数据,并将它们添加到list容器中。
具体的实现步骤如下所示:
1. 将需要转换的字符串string先转换成sstream对象,方便后续的读取操作。
2. 定义一个list容器list<long>,用于存储读取的long类型数据。
3. 使用while循环读取stringstream对象中的每一个long类型数据,直到遇到字符串末尾的标记。
4. 读取每一个long类型数据之前使用stringstream对象的peek()方法来判断是否到达字符串末尾。
5. 使用stringstream对象的extract()方法逐个读取long类型数据,并将其添加到list容器中。
6. 读取完成后,关闭stringstream对象,并返回最终的list<long>集合对象。
下面是具体的实现代码:
```
#include <iostream>
#include <sstream>
#include <string>
#include <list>
using namespace std;
list<long> stringToList(const string& str) {
list<long> lst;
stringstream ss(str);
while (ss.peek() != EOF) {
long num;
ss >> num;
lst.push_back(num);
}
ss.clear();
return lst;
}
int main() {
string str = "123 456 789";
list<long> lst = stringToList(str);
for (const auto& num : lst) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
以上就是将string字符串转换为list<long>集合的实现过程,利用stringstream对象进行逐个读取,可以很方便地将字符串转换成任意类型的容器。
把long数据转换成list集合
可以使用list()函数将long数据转换成list集合,示例代码如下:
```python
long_data = 1234567890123456789
list_data = list(str(long_data))
print(list_data)
```
输出结果:
```
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
```
首先将long数据转换成字符串,然后使用list()函数将字符串转换成list集合。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)