我在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吗?我知道这是微不足道的,但这似乎很奇怪,没有本地直接进行转换。
当前回答
我更喜欢切换方法。 性能与c - '0'相同,但我发现开关更容易阅读。
基准:
Method | Mean | Error | StdDev | Allocated Memory/Op |
---|---|---|---|---|
CharMinus0 | 90.24 us | 7.1120 us | 0.3898 us | 39.18 KB |
CharSwitch | 90.54 us | 0.9319 us | 0.0511 us | 39.18 KB |
代码:
public static int CharSwitch(this char c, int defaultvalue = 0) {
switch (c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default: return defaultvalue;
}
}
public static int CharMinus0(this char c, int defaultvalue = 0) {
return c >= '0' && c <= '9' ? c - '0' : defaultvalue;
}
其他回答
我见过很多答案,但我觉得很困惑。我们不能简单地使用类型转换吗?
例:-
int s;
char i= '2';
s = (int) i;
我更喜欢切换方法。 性能与c - '0'相同,但我发现开关更容易阅读。
基准:
Method | Mean | Error | StdDev | Allocated Memory/Op |
---|---|---|---|---|
CharMinus0 | 90.24 us | 7.1120 us | 0.3898 us | 39.18 KB |
CharSwitch | 90.54 us | 0.9319 us | 0.0511 us | 39.18 KB |
代码:
public static int CharSwitch(this char c, int defaultvalue = 0) {
switch (c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default: return defaultvalue;
}
}
public static int CharMinus0(this char c, int defaultvalue = 0) {
return c >= '0' && c <= '9' ? c - '0' : defaultvalue;
}
char c = '1';
int i = (int)(c - '0');
你可以用它创建一个静态方法:
static int ToInt(this char c)
{
return (int)(c - '0');
}
有一个非常简单的方法可以将字符0-9转换为整数: c#像对待整数一样对待char值。
Char c = '7';(ascii码55)int x = c - 48;(result = integer of 7)
使用Uri.FromHex。 为了避免异常Uri.IsHexDigit。
char testChar = 'e';
int result = Uri.IsHexDigit(testChar)
? Uri.FromHex(testChar)
: -1;