2
static void Main(string[] args)
{
    string foo = "jason123x40";
    char[] foo2 = foo.ToCharArray();
    string foo3 = "";

    for (int i = 0; i < foo2.Length; i++)
    {
        int num = 0;
        Int32.TryParse(foo2[i].ToString(), out num);
        if (num != 0)
        {
            foo3 += num.ToString();
        }
    }
    Console.WriteLine(foo3);
    Console.ReadLine();
}

So lets say I have a string called "john10smith250". The result should be "10250". However I would get "125" instead with my code.

The reason I filtered out the 0 was because I didn't want any non numeric characters to be treated as a zero.

Is there a better way to convert a part of a string into an int?

1
  • 3
    You're explicitly not counting '0', so you shouldn't be surprised that you don't have any in your result... Also, char.IsNumber(char). You're using TryParse incorrectly. If it failed it returns false. Commented Jan 15, 2014 at 3:59

7 Answers 7

9

Using LINQ :

var myString = "john10smith250";
var myNumbers = myString.Where(x => char.IsDigit(x)).ToArray();
var myNewString = new String(myNumbers);
Sign up to request clarification or add additional context in comments.

8 Comments

Uhm, where is x defined? I'm not really sure on how to use LINQ.
@puretppc x represents each charachter in your string
@puretppc, if you are asking where is the var x = blah there is none. Its declared in the x => and used inline. Its scope is only in those parens.
@puretppc, if you don't know linq and lambda statements,you should learn.as you see they are cool and they save you from lot of work :)
@puretppc I'm not expert on efficiency but it depends I think.In your case probably it doesn't matter.But on largest lists it should matter.Less code would be less painful
|
4

You've got a couple of good solutions that change the approach and shorten your code. For completeness, here is how you make your code work.

Your code assumes that if the num is zero, the parse has failed:

int num = 0;
Int32.TryParse(foo2[i].ToString(), out num);
if (num != 0) // This is wrong
{
    foo3 += num.ToString();
}

You need to change the code like this:

int num = 0;
if (Int32.TryParse(foo2[i].ToString(), out num))
{
    foo3 += num.ToString();
}

The reason your code did not work was that you ignored the return value of TryParse. It returns false if the parse fails, or true if the parse succeeds, even if the number being parsed is zero. In fact, that's the reason behind TryParse taking an out parameter (as opposed to returning the value directly, the way the Int32.Parse does).

Comments

2

use :

var str= "jason123x40";
var number=  str.Where(x => char.IsDigit(x)).Select(x => x);

Comments

2

Pretty close to what you have there...

int parseNumbersFromString(string data)
{
    string number = "";

    for(int i = 0; i < data.Length; ++i)
    {
        if(char.IsDigit(data[i]))
            number += data[i];
    }
    return Convert.ToInt32(number);
}

Comments

2

You can solve it by using Regx

\d+ is the regex for an integer number.

So

string outputstring = Regex.Match(yourstring, @"\d+").Value;

will give you that number as a string. Int32.Parse(outputstring) will then give you the number.

or you can do like this

go through the string and use Char.IsDigit

string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}
if (b.Length>0)
{
    val = int.Parse(b);
}

Comments

1

*You can use index to access a char in a string
*IsDigit check if this char is a digit then append it to the string foo2 if condition is true

string foo = "jason0123x40";
string foo2 = "";

for (int i = 0; i < foo.Length; i++)
{
    if (char.IsDigit(foo[i]))
        foo2 += foo[i];
}
Console.WriteLine(foo2);
Console.ReadLine();

3 Comments

You're a little late but thanks anyways for this. +1 :)
No problem, I just notice that you are not familiar with Lambda expression and Linq and tried to give you more efficient alternative.
Yeah I consider both of them. At least it's helpful in case people find this question so they can try whichever one they like. :)
0

You can use a regular expression as follows:

string foo = "jason123x40";
string foo3 = Regex.Replace(foo, @"\D", "");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.