[英]How to cast an 'int' to a 'char' in C#?
I have a string variable which has a mixture of numbers and letters. 我有一个字符串变量,其中包含数字和字母。 I want to create a new string that only has int
values of the previous string variable. 我想创建一个仅具有前一个字符串变量的int
值的新字符串。 So I found two ways to cast int
to char
. 所以我找到了两种将int
为char
。 However, they do not work. 但是,它们不起作用。 Here's what I've tried 这是我尝试过的
string onlyNumberString = "";
foreach (char onlyNum in puzzleData)
{
for (int i = 1; i < 10; i++)
{
if (onlyNum == (char)i)
{
onlyNumberString += onlyNum;
}
}
}
and 和
string onlyNumberString = "";
foreach (char onlyNum in puzzleData)
{
for (int i = 1; i < 10; i++)
{
if (onlyNum == Convert.ToChar(i))
{
onlyNumberString += onlyNum;
}
}
}
Use Char.IsDigit instead, far simpler. 使用Char.IsDigit代替,简单得多。
StringBuilder onlyNumber = new StringBuilder();
foreach (char onlyNum in puzzleData)
{
if (Char.IsDigit(onlyNum))
{
onlyNumber.Append(onlyNum);
}
}
You can just cast an int
to a char
it directly: 您可以直接将int
转换为char
:
var myChar = (char)20;
But to do what you want I suggest using a regular expression: 但是要做你想做的事,我建议使用正则表达式:
var onlyNumerals = Regex.Replace(myString, @"[^0-9]", "");
The above will replace any character that is not 0-9 with an empty space. 上面的代码将所有非0-9的字符替换为空白。
An alternative, using LINQ and char.IsDigit
: 另一种选择,使用LINQ和char.IsDigit
:
var onlyNumeral = new string(myString.Where(c => Char.IsDigit(c)).ToArray());
int iNum = 2;
char cChar = iNum.ToString()[0];
Will work for x when 0 <= x <= 9. 当0 <= x <= 9时适用于x。
您可以按照以下方式进行操作:
string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
A few ways: 几种方法:
(char)int
Or 要么
int.Parse(char.ToString())
Or 要么
Convert.ToChar(int);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.