我剛纔問了一個關於如何將數字轉換爲前導零的字符串的問題。我有一些很好的答案。非常感謝。我真的不知道哪個標記是正確的,因爲它們都很好。對不起,我沒有標記正確的人。將字符串轉換爲c中的整數#
現在我有一個像
001
002
003
字符串如何轉換到整數?類似於Key = i.ToString(「D2」)的反義詞;
曼迪
我剛纔問了一個關於如何將數字轉換爲前導零的字符串的問題。我有一些很好的答案。非常感謝。我真的不知道哪個標記是正確的,因爲它們都很好。對不起,我沒有標記正確的人。將字符串轉換爲c中的整數#
現在我有一個像
001
002
003
字符串如何轉換到整數?類似於Key = i.ToString(「D2」)的反義詞;
曼迪
很容易也。
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)
}
int number = int.Parse(string)
或
int number;
int.TryParse(string, out number)
您需要解析將字符串轉換爲整數
Int32.Parse("001");
int i;
int.TryParse(stringValue, out i)
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
}
這裏是:
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
}
快速的問題 - 你假設基數爲10?因爲我已經看到前導0號碼是其他基礎,如八進制。 – n8wrl 2011-03-24 12:00:08