我在c#中有一个char:

char foo = '2';

现在我想把2变成一个整型。我发现皈依。ToInt32返回该字符的实际十进制值,而不是数字2。以下是可行的方法:

int bar = Convert.ToInt32(new string(foo, 1));

int。解析也只适用于字符串。

c#中没有本地函数可以在不使其成为字符串的情况下从char转换为int吗?我知道这是微不足道的,但这似乎很奇怪,没有本地直接进行转换。


当前回答

我同意@Chad Grant的观点

同样正确,如果你转换为字符串,那么你可以使用该值作为问题中所说的数字

int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2

我试图创建一个更简单易懂的例子

char v = '1';
int vv = (int)char.GetNumericValue(v); 

char.GetNumericValue(v)返回double值并转换为(int)

作为数组的更高级用法

int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();

其他回答

这将转换为整数并处理unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

你可以在这里阅读更多。

这将把它转换为int型:

char foo = '2';
int bar = foo - '0';

这是可行的,因为每个字符在内部都由一个数字表示。字符“0”到“9”由连续的数字表示,因此找出字符“0”和“2”之间的差值,结果是数字2。

我搜索了最优化的方法,并非常惊讶地发现,最好的方法是最简单的(也是最流行的答案):

public static int ToIntT(this char c) =>
    c is >= '0' and <= '9'?
        c-'0' : -1;

下面是我尝试过的一些方法:

c-'0' //current
switch //about 25% slower, no method with disabled isnum check (it is but performance is same as with enabled)
0b0000_1111 & (byte) c; //same speed
Uri.FromHex(c) /*2 times slower; about 20% slower if use my isnum check*/ (c is >= '0' and <= '9') /*instead of*/ Uri.IsHexDigit(testChar)
(int)char.GetNumericValue(c); // about 20% slower. I expected it will be much more slower.
Convert.ToInt32(new string(c, 1)) //3-4 times slower

请注意,isnum检查(第一个代码块中的第二行)占用了大约30%的性能,所以如果您确定c是char,则应该取消它。测试误差为~5%

试试这个

char x = '9'; // '9' = ASCII 57

int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9

有一个非常简单的方法可以将字符0-9转换为整数: c#像对待整数一样对待char值。

Char c = '7';(ascii码55)int x = c - 48;(result = integer of 7)