Sarp Kaya
Sarp Kaya

Reputation: 3794

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. So I found two ways to cast int to 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;
        }
    }
}

Upvotes: 1

Views: 12920

Answers (5)

user1425647
user1425647

Reputation: 66

You can do it as:

string justNumbers = new String(text.Where(Char.IsDigit).ToArray());

Upvotes: 2

Oded
Oded

Reputation: 499382

You can just cast an int to a char it directly:

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.

An alternative, using LINQ and char.IsDigit:

 var onlyNumeral = new string(myString.Where(c => Char.IsDigit(c)).ToArray());

Upvotes: 3

dtsg
dtsg

Reputation: 4459

A few ways:

(char)int

Or

int.Parse(char.ToString())

Or

Convert.ToChar(int);

Upvotes: -2

Jeff Watkins
Jeff Watkins

Reputation: 6357

Use Char.IsDigit instead, far simpler.

StringBuilder onlyNumber = new StringBuilder();
foreach (char onlyNum in puzzleData)
{
    if (Char.IsDigit(onlyNum))
    {
        onlyNumber.Append(onlyNum);
    }
}

Upvotes: 4

Shai
Shai

Reputation: 25595

int iNum = 2;

char cChar = iNum.ToString()[0];

Will work for x when 0 <= x <= 9.

Upvotes: 3

Related Questions