C# 将字符串或字符转换为int

C# 将字符串或字符转换为int,c#,type-conversion,C#,Type Conversion,我完全迷惑不解 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=280555和51是它们在ascii图表中的位置。 链接至图表- 尝试使用int.parse这是字符7和3的ASC

我完全迷惑不解

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图表中的位置。 链接至图表-


尝试使用
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()
将字符或字符串转换为值

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()
计算效率更高:


将字符转换为整数将获得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]
是值

从方法

将指定的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);

下面是一个

将字符转换回字符串,您将得到“所需”结果:
int tempc0=Convert.ToInt32(temp[0].ToString());int tempc1=Convert.ToInt32(temp[1].ToString())
A char是隐式数字,并且该数字与子字符串的int表示形式无关。将数字字符转换为int的最快方法是使用
temp[0]-“0”
。请参阅我的答案,以获取此示例。是的,它还需要ToString()
int.Parse(temp[0].ToString())
@TimSchmelter-我不想从调试中获得所有乐趣;)
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);