我完全不解将字符串或字符为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