[英]Converting string or char to 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
55和51是它們在ascii圖表中的位置。 鏈接到圖表 - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
嘗試使用int.parse
這是字符7和3的ASCII值。如果您想要數字表示,那么您可以將每個字符轉換為字符串,然后使用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);
這有效:
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()
將char或string轉換為值。
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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.