2011-03-24 48 views
3

我剛纔問了一個關於如何將數字轉換爲前導零的字符串的問題。我有一些很好的答案。非常感謝。我真的不知道哪個標記是正確的,因爲它們都很好。對不起,我沒有標記正確的人。將字符串轉換爲c中的整數#

現在我有一個像

001 
002 
003 

字符串如何轉換到整數?類似於Key = i.ToString(「D2」)的反義詞;

曼迪

+2

快速的問題 - 你假設基數爲10?因爲我已經看到前導0號碼是其他基礎,如八進制。 – n8wrl 2011-03-24 12:00:08

回答

7

很容易也。

string myString = "003"; 
int myInt = int.Parse(myString); 

如果你是不知道,如果字符串是有效的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) 
} 
1
int number = int.Parse(string) 

int number; 
int.TryParse(string, out number) 
0

您需要解析將字符串轉換爲整數

Int32.Parse("001"); 
0
int i; 
int.TryParse(stringValue, out i) 
2
string strNum= "003"; 
int myInt; 
if(int.TryParse(myString, out myInt) 
{ 
    //here you can print myInt 
}else{ 
    //show error message if strNum is invalid integer string 
} 
1

這裏是:

int i; 

if (Int32.TryParse("003", i)) 
{ 
    // Now you have the number successfully assigned to i 
} 
else 
{ 
    // Handle the case when the string couldn't be converted to an int 
}