我完全不解將字符串或字符爲int
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
我希望:7*3=21
但後來我收到:55*51=2805
我完全不解將字符串或字符爲int
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
我希望:7*3=21
但後來我收到:55*51=2805
這是字符7和ASCII值3.如果要數表示,那麼你可以將每個字符轉換爲字符串,然後使用Convert.ToString
:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
第一個完美的解決方案,謝謝 – fishmong3r 2013-03-14 09:11:35
@ fishmong3r,不客氣 – Habib 2013-03-14 09:11:53
55和51是其ASCII表中的位置。 鏈接到圖表 - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
嘗試使用int.parse
'int.Parse'僅適用於字符串,不適用於字符;) – 2013-03-14 08:59:21
是的,它也需要ToString()'int.Parse(temp [0] .ToString());' – fishmong3r 2013-03-14 09:02:01
@TimSchmelter - 我不喜歡把所有的樂趣拿出來調試一下;) – Sayse 2013-03-14 10:15:17
這工作:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
你要做的ToString()來獲得實際字符串表示。
您將得到7和3的ASCII碼,分別是55和51。使用int.Parse()
將字符或字符串轉換爲值。
int tempc0 = int.Parse(temp[0].ToString());
int tempc1 = int.Parse(temp[1].ToString());
int product = tempc0 * tempc1; // 7 * 3 = 21
int.Parse()
不接受char
作爲參數,所以你要轉換爲string
第一,或使用temp.SubString(0, 1)
代替。
這工作,並且比使用任何int.Parse()
或Convert.ToInt32()
計算效率更高:
string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
轉換字符爲整數讓你的Unicode字符代碼。如果您將字符串轉換爲整數它會被解析爲一個號碼:
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));
當你寫string temp = "73"
,你temp[0]
和temp[1]
正在char
值。
從Convert.ToInt32 Method(Char)
方法
指定的Unicode字符的給 等效 32位帶符號整數的值轉換。
這意味着轉換char
到int32
給你的Unicode字符代碼。
您只需要使用.ToString()
方法您的temp[0]
和temp[1]
值。喜歡;
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
這裏是一個DEMO。
將字符轉換回字符串,您將得到您想要的結果:int tempc0 = Convert.ToInt32(temp [0] .ToString()); int tempc1 = Convert.ToInt32(temp [1] .ToString());'一個char是隱式數字,這個數字與你的子串的整型表示無關。 – 2013-03-14 08:57:35
將數字字符轉換爲整數的最快方法是使用'temp [0] - '0'。看到我的答案爲例。 – JLRishe 2013-03-14 09:05:02