在许多编程语言中,将字符串转换为整数类型(int)是一个常见的操作,下面是一些常见编程语言的转换方法:
1. **Python**:
s = "123" num = int(s)
2. **JavaScript**:
let s = "123"; let num = parseInt(s); // 或者使用 Number() 函数
3. **Java**:
String s = "123"; int num = Integer.parseInt(s); // 或者使用 Integer.valueOf() 方法
4. **C#**:
string s = "123"; int num = Int32.Parse(s); // 或者使用 Int32.TryParse() 方法,后者更为安全
5. **C++**:
#include <string> #include <sstream> #include <stdexcept> std::string s = "123"; std::stringstream ss(s); int num; ss >> num; // 如果字符串不能转换为整数,会抛出异常
6. **Ruby**:
s = "123" num = s.to_i # 或者使用 Integer(s) 方法,后者更为安全
7. **PHP**:
$s = "123"; $num = intval($s); // 或者使用 (int) 强制类型转换
8. **Go**:
Go语言中没有内置的字符串到整数的转换函数,但你可以使用strconv包中的Atoi函数进行转换,`strconv.Atoi("123")`,如果字符串不能转换为整数,Atoi会返回错误,你需要处理这个错误。