如何将整数字符串转换为整数 [英] how to convert an integer string to an integer

查看:95
本文介绍了如何将整数字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将整数字符串转换为整数

解决方案

您可以使用 Convert.ToInt < a href =http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx> [ ^ ]方法(选择适当的重载)。



如果你是不确定字符串是否为整数,请考虑使用 TryParse [ ^ ]。


尽量避免 Parse(...) Convert.ToInt(...)

请改用 TryParse(...)

原因:只有 TryParse(...)允许对解析不匹配做出反应,其他两个函数在这种情况下抛出异常。



E. G。如果您尝试解析并在发生解析失败时设置为默认值,则可以使用以下内容:

  static   readonly   int  DEFAULT_FOR_V =  123 ; 
...
string s = ...;
...
int v = int TryParse(s , out v)? v:DEFAULT_FOR_V;
...





干杯

Andi


使用 int.Parse()

  string  str =   123456; 
int i = int .Parse(str);


how to convert an integer string to an integer

解决方案

You can use the Convert.ToInt[^] method (choose the appropriate overload).

If you are not sure if the string is an integer or not, consider using TryParse[^].


Try to avoid Parse(...) or Convert.ToInt(...).
Use TryParse(...) instead.
Reason: only TryParse(...) allows to react on parsing mismatches, the other two functions throw exceptions in that case.

E.g. If you try to parse and set to a default in case of a parse failure occurs, you may use the following:

static readonly int DEFAULT_FOR_V = 123;
...
string s = "...";
...
int v = int.TryParse(s, out v) ? v : DEFAULT_FOR_V;
...



Cheers
Andi


Use int.Parse():

string str = "123456";
int i = int.Parse(str);


这篇关于如何将整数字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆