将字符串或字符转换为整数

8

我完全不知所措

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

2
将字符转换回字符串,即可获得所需的结果:int tempc0 = Convert.ToInt32(temp[0].ToString()); int tempc1 = Convert.ToInt32(temp[1].ToString());字符隐式地是数字,而该数字与您子字符串的 int 表示形式无关。 - Tim Schmelter
1
将数字字符转换为整数的最快方法是使用 temp[0] - '0'。请参阅我的答案以获取示例。 - JLRishe
7个回答

5

2
是的,它还需要ToString() int.Parse(temp[0].ToString()); - fishmong3r
1
@TimSchmelter - 我不喜欢把调试的乐趣都剥夺掉 ;) - Sayse

5

这是字符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);

1
这个可以工作:

    string temp = "73";
    int tempc0 = Convert.ToInt32(temp[0].ToString());
    int tempc1 = Convert.ToInt32(temp[1].ToString());
    Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);           

你需要执行 ToString() 方法来获取实际的字符串表示。

1
你正在获取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)


1

这个方法可行,而且比使用 int.Parse() 或者 Convert.ToInt32() 更加计算效率高:

string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);

1
将字符转换为整数会给出Unicode字符代码。如果您将字符串转换为整数,则会将其解析为数字:
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));

1
当你写下 string temp = "73" 时,你的 temp[0]temp[1]char 值。
来自 Convert.ToInt32 Method(Char) 方法:

将指定 Unicode 字符的值转换为等效的 32 位有符号整数。

这意味着将一个 char 转换成 int32 将会得到该字符的 Unicode 编码。
你只需要对你的 temp[0]temp[1] 值使用 .ToString() 方法。例如:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);

这里有一个DEMO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接