如何将整数字符串转换为整数 [英] how to convert an integer string to an integer
本文介绍了如何将整数字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将整数字符串转换为整数
解决方案
您可以使用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 theConvert.ToInt
[^] method (choose the appropriate overload).
If you are not sure if the string is an integer or not, consider usingTryParse
[^].
Try to avoidParse(...)
orConvert.ToInt(...)
.
UseTryParse(...)
instead.
Reason: onlyTryParse(...)
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
Useint.Parse()
:
string str = "123456"; int i = int.Parse(str);
这篇关于如何将整数字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文