panjo
panjo

Reputation: 3515

convert string to int with losing everything but digits

I have string

string a = "234234324\r\n";

I want to parse this string into integer with losing this \r\n part, so int should contain only digits from string a like int b = 234234324;

p.s. string does not necessarily contain the \r\n part, point is that I want to use only digits from string.

I tried with Convert.ToInt32(a) but I have error.

Upvotes: 1

Views: 117

Answers (5)

Alex Filipovici
Alex Filipovici

Reputation: 32561

Try this (you need to add a reference to Microsoft.VisualBasic):

using Microsoft.VisualBasic;

class Program
{
    static void Main(string[] args)
    {
        var a = "234234324\r\n";
        int b = int.Parse(Conversion.Val(a).ToString());
    }
}

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

You must use Trim followed by Int32.TryParse

int b = Int32.TryParse(a.Trim(), out num);

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34846

Try this:

string a = "234234324\r\n";
string justNumbers = new String(a.Where(Char.IsDigit).ToArray());

Note: Obviously, this requires LINQ.

Now you can convert the string without fear of non-numerics being in the string, like this:

Convert.ToInt32(justNumbers);

Upvotes: 2

It'sNotALie.
It'sNotALie.

Reputation: 22794

int b = int.Parse(new string(a.Where(char.IsDigit).ToArray()));

Upvotes: 8

McGarnagle
McGarnagle

Reputation: 102753

You just need Trim -- that removes all leading and trailing whitespace.

int b = int.Parse(a.Trim());

Upvotes: 7

Related Questions