4

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.

4
  • 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... Commented Jul 8, 2009 at 15:06
  • I don't understand your question. atoi would return 26 with either string. Commented Jul 8, 2009 at 15:12
  • 26things without a space doesn't have a space so ATOI would try to parser not only 26 but the whole string isn't? Commented Jul 8, 2009 at 15:17
  • 1
    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. Commented Jul 8, 2009 at 15:23

10 Answers 10

13

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);
9
  • +1 beat me to it. Regex works too but I was going with this for practice. Also meets the OPs clarified requirements. Commented Jul 8, 2009 at 15:03
  • 1
    I love this answer. It matches the spirit of atoi. I just think it's a little hard to read, at least for me, so I accepted the regex. Commented Jul 8, 2009 at 15:10
  • 1
    +1. I prefer the LINQ over Regex. You can also improve on this by adding a SkipWhile to ignore any text before the number (in case of "There are 26 things") and it would be even more robust. Commented Jul 8, 2009 at 15:11
  • 1
    To completely match the atoi functionality, you should first trim the string. Commented Jul 8, 2009 at 15:19
  • 2
    @C.B. you can even shorten that to int.Parse(new string(str.Trim().TakeWhile(char.IsDigit).ToArray()))
    – Timbo
    Commented May 30, 2013 at 18:38
10

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;
15
  • 13
    Oh please, no regex for such a trivial task.
    – Noldorin
    Commented Jul 8, 2009 at 14:49
  • 3
    @Noldorin - Why not, it's a perfectly valid use of regex. I'm not sure why this needs a down-vote just because you would do it differently? Commented Jul 8, 2009 at 14:52
  • 2
    @Noldorin: Why not? For simple tasks like these, the regex is actually easily readable. To be honest, I find it clearer than your solution. Commented Jul 8, 2009 at 14:59
  • 2
    @Noldorin - Simple text manipulation will not work as efficiently nor as simply as a regular expression in this case. I agree that regular expressions can be abused, but this is a great case for using one. Commented Jul 8, 2009 at 14:59
  • 2
    To match atoi, the regex should be ^\s*\d+ Commented Jul 8, 2009 at 15:16
2

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

1
  • That would work for me. I was wondering if there was a more atoi-like answer that didn't require the number to be followed by a space. Commented Jul 8, 2009 at 14:54
1

one way would be

string sample = "26 things";
int x = int.Parse(sample.Substring(0, sample.IndexOf(" ")));
2
  • doesn't work with "26things" which would be no problem for atoi Commented Jul 8, 2009 at 14:59
  • Lame excuse but let me try: That was not the requirement.
    – schar
    Commented Jul 8, 2009 at 15:10
0

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

5
  • I think you might have to write a specific function yourself to grab the number part, perhaps using the .NET String.Substring() function..?
    – Phill
    Commented Jul 8, 2009 at 14:49
  • It throws an exception on non-numeric data. Commented Jul 8, 2009 at 14:49
  • Yeah - that's what I suspected. Commented Jul 8, 2009 at 15:00
  • @Jeremy Stein: use int.TryParse() instead Commented Jul 8, 2009 at 15:00
  • @Jasper Bekkers: TryParse would give me 0. Commented Jul 8, 2009 at 15:21
0

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

1
  • 1
    It returns 26123 for the string "26 123" which is not what atoi would do.
    – Timbo
    Commented Jul 8, 2009 at 15:02
0

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

Try this:

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

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
  • 1
    I would argue if you're going to take that path then you should just use regular expressions.
    – Kenny Mann
    Commented Jul 8, 2009 at 14:52
  • 1
    Well, you maybe right... but anyway my solution is better than the ones using .IndexOf(" ") Commented Jul 8, 2009 at 14:55
-2

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

var str = "26 things";
var count = int.Parse(str.Split(' ')[0]);
5
  • 1
    what for a string like 26things? Commented Jul 8, 2009 at 14:51
  • Such a format was not specified in the question. If it is possible, the question needs to be clarified.
    – Noldorin
    Commented Jul 8, 2009 at 14:54
  • 1
    This is not in the requirement first of all.. with ATOI the guy whould have to specify the pointer length too. This is a valid option. Commented Jul 8, 2009 at 14:56
  • 1
    @Noldorin - Not true, he asked 'What's the easiest way to grab the integer from the beginning of a string?', and 26things fits this criteria. Thre is no mention of a format other than integer at begining of string! Commented Jul 8, 2009 at 14:57
  • Well, I did say equivalent to atoi in the title. I'll clarify. Commented Jul 8, 2009 at 14:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.