在c#中将字符串转换为整数

Man*_*ton 3 c#

我刚问了一个关于如何将数字转换为带前导零的字符串的问题.我有一些很棒的答案.非常感谢.我真的不知道哪个标记正确,因为它们都很好.对不起那些我没记错的人.

现在我有类似的字符串

001
002
003
Run Code Online (Sandbox Code Playgroud)

如何转换回整数?与Key = i.ToString("D2")相反的东西;

曼迪

Øyv*_*hen 7

也很容易.

string myString = "003";
int myInt = int.Parse( myString );
Run Code Online (Sandbox Code Playgroud)

如果您不确定该字符串是否为有效的int,您可以这样做:

string myString = "003";
int myInt;
if( int.TryParse( myString, out myInt )
{
  //myString is a valid int and put into myInt
}else{
  //myString could not be converted to a valid int, and in this case myInt is 0 (default value for int)
}
Run Code Online (Sandbox Code Playgroud)