4
votes

If I have a string like:

"26 things"

I want to convert it to 26. I just want the integer at the beginning of the string.

If I was using C, I'd just use the atoi function. But I can't seem to find anything equivalent in .NET.

What's the easiest way to grab the integer from the beginning of a string?

Edit: I'm sorry I was ambiguous. The answers that look for a space character in the string will work in many circumstances (perhaps even mine). I was hoping for an atoi-equivalent in .NET. The answer should also work with a string like "26things". Thanks.

10
I am curious to see how you do that with ATOI() with the space and without the space. You can't just call ATOI(yourString)... because the function first discards as many whitespace characters as necessary until the first non-whitespace character is found...Patrick Desjardins
I don't understand your question. atoi would return 26 with either string.Jeremy Stein
26things without a space doesn't have a space so ATOI would try to parser not only 26 but the whole string isn't?Patrick Desjardins
atoi will stop at the first non-digit. So 26things would parse to 26. atoi only considers whitespace in that it skips over the initial whitespace. Once it finds the number, it will stop at any non-digit character. 26.9 would parse to 26.Jeremy Stein

10 Answers

14
votes

This looks sooo beautiful:

string str = "26 things";
int x = int.Parse(str.TakeWhile(ch => char.IsDigit(ch)).Aggregate("", (s, ch) => s + ch));

And, the boring solution for anyone who really wants atoi:

[System.Runtime.InteropServices.DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int atoi(string str);
10
votes

This should work (edited to ignore white-space at the begining of the string)

int i = int.Parse(Regex.Match("26 things", @"^\s*(\d+)").Groups[1].Value);

If you are worried about checking if there is a value you could do the following to give you a -1 value if there is no integer at the begining of the string.

Match oMatch = Regex.Match("26 things", @"^\s*(\d+)");
int i = oMatch.Success ? int.Parse(oMatch.Groups[1].Value) : -1;
2
votes

You could use Int32.Parse(stringVal.Substring(0, stringVal.indexOf(" "))

1
votes

one way would be

string sample = "26 things";
int x = int.Parse(sample.Substring(0, sample.IndexOf(" ")));
0
votes

The direct equivalent is int.Parse(string) but I'm not entirely sure if that will take just the starting number.

0
votes

You can call Val in the Microsoft.VisualBasic.Conversion namespace. In your scenario it should print "26". I don't know if it's 100% compatible in toher scenarios though. Here's a link to the specification.

http://msdn.microsoft.com/en-us/library/k7beh1x9%28VS.71%29.aspx

0
votes

If you want only whole number

public String GetNumber (String input)
{
    String result = "";
    for (Int32 i = 0; i < input.Length; i++)
    {
        if (Char.IsNumber(input[i]))
        {
            result += input[i];
        }
        else break;
    }
    return result;
}
-1
votes

Try this:

int i = int.Parse("26 things".Split(new Char[] {' '})[0]);
-2
votes

I can think just in something like this:

    public static string Filter(string input, string validChars) {
        int i;
        string result = "";
        for (i = 0; i < input.Length; i++) {
            if (validChars.IndexOf(input.Substring(i, 1)) >= 0) {
                result += input.Substring(i, 1);
            } else break;
        }
        return result ;
    }

And call it :

Filter("26 things", "0123456789");
-2
votes

You've got to split the string and then parse it:

var str = "26 things";
var count = int.Parse(str.Split(' ')[0]);