如何在c#中从字符串转换为整数? [英] how to convert from string to integer in c# ?

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

问题描述

如何在c#中从字符串转换为整数?

how to convert from string to integer in c# ?

推荐答案

转换中非常有趣的事情是输入字符串,这里有一些例子来了解转换..



1.
Very interesting thing in conversion is Input string, here some examples to understand convertion..

1.
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105



2.


2.

int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105



3.


3.

try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.



4.


4.

string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int.





从上面的例子中你可以知道输入字符串的格式应该是正确的 ..



您可以参考以下链接..

http://msdn.microsoft.com/en-us/library/bb397679.aspx [ ^ ]


使用Int32.TryParse [ ^ ]或 Inst32.Parse [ ^ ]

use Int32.TryParse[^] or Inst32.Parse[^]
int number;
bool result = Int32.TryParse("string value to convert", out number);
//or
number = Int32.Parse("string value to convert");


int number = Convert.ToInt32("string to convert");


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

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