我在c#中有一个char:
char foo = '2';
现在我想把2变成一个整型。我发现皈依。ToInt32返回该字符的实际十进制值,而不是数字2。以下是可行的方法:
int bar = Convert.ToInt32(new string(foo, 1));
int。解析也只适用于字符串。
c#中没有本地函数可以在不使其成为字符串的情况下从char转换为int吗?我知道这是微不足道的,但这似乎很奇怪,没有本地直接进行转换。
我在c#中有一个char:
char foo = '2';
现在我想把2变成一个整型。我发现皈依。ToInt32返回该字符的实际十进制值,而不是数字2。以下是可行的方法:
int bar = Convert.ToInt32(new string(foo, 1));
int。解析也只适用于字符串。
c#中没有本地函数可以在不使其成为字符串的情况下从char转换为int吗?我知道这是微不足道的,但这似乎很奇怪,没有本地直接进行转换。
当前回答
我见过很多答案,但我觉得很困惑。我们不能简单地使用类型转换吗?
例:-
int s;
char i= '2';
s = (int) i;
其他回答
当字符不是ASCII数字时,基于结果的一些方法的比较:
char c1 = (char)('0' - 1), c2 = (char)('9' + 1);
Debug.Print($"{c1 & 15}, {c2 & 15}"); // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}"); // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}"); // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}"); // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1
用这个:
public static string NormalizeNumbers(this string text)
{
if (string.IsNullOrWhiteSpace(text)) return text;
string normalized = text;
char[] allNumbers = text.Where(char.IsNumber).Distinct().ToArray();
foreach (char ch in allNumbers)
{
char equalNumber = char.Parse(char.GetNumericValue(ch).ToString("N0"));
normalized = normalized.Replace(ch, equalNumber);
}
return normalized;
}
这招对我很管用:
int bar = int.Parse("" + foo);
真正的方法是:
int theNameOfYourInt = (int).Char.GetNumericValue(theNameOfYourChar);
" namameofyourint " -你想要你的char被转换成的int。
" namameofyourchar " -你想要使用的Char,因此它将被转换为int型。
其他的都不要管。
我搜索了最优化的方法,并非常惊讶地发现,最好的方法是最简单的(也是最流行的答案):
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%