String转换成long
时间: 2023-07-08 11:26:45 浏览: 73
可以使用Java的内置函数`Long.parseLong(String s)`将String类型转换为long类型。例如:
```java
String str = "12345";
long num = Long.parseLong(str);
```
其中,`str`为要转换的字符串,`num`为转换后的long类型变量。请注意,如果字符串中包含非数字字符,则会抛出`NumberFormatException`异常。
相关问题
string 转换方法
string 转换方法有很多种,可以根据具体需求选择合适的方法。以下是几种常用的转换方法:
1. 使用 stoi() 函数将字符串转换为整数:
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << num << std::endl; // 输出 12345
return 0;
}
```
2. 使用 stof() 函数将字符串转换为浮点数:
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "3.14";
float num = std::stof(str);
std::cout << num << std::endl; // 输出 3.14
return 0;
}
```
3. 使用 to_string() 函数将整数或浮点数转换为字符串:
```cpp
#include <string>
#include <iostream>
int main() {
int num1 = 12345;
std::string str1 = std::to_string(num1);
std::cout << str1 << std::endl; // 输出 "12345"
float num2 = 3.14;
std::string str2 = std::to_string(num2);
std::cout << str2 << std::endl; // 输出 "3.140000"
return 0;
}
```
以上是一些常用的字符串转换方法,根据具体需求选择适合的方法即可。
list string转换
列表(List)和字符串(String)之间的转换可以使用Java提供的方法来实现。下面是两种常用的方法:
1. 使用Arrays.asList()方法将字符串转换为列表。以下是一个示例代码:
```java
String text = "huhantain,taiyangshen,nodeli";
List<String> list = Arrays.asList(text.split(","));
System.out.println(list);
```
运行结果为:[huhantain, taiyangshen, nodeli]
2. 使用String.join()方法将列表转换为字符串。以下是一个示例代码:
```java
List<String> list = new ArrayList<>();
list.add("huhantain");
list.add("taiyangshen");
list.add("nodeli");
String join = String.join(",", list);
System.out.println(join);
```
运行结果为:huhantain,taiyangshen,nodeli
另外,如果你想要将字符串按照空格分割成一个列表,可以使用split()方法。以下是一个示例代码:
```python
String str2 = "123 sjhid dhi";
String[] list2 = str2.split(" ");
System.out.println(Arrays.toString(list2));
```
运行结果为:[123, sjhid, dhi]
相关推荐
![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_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)