Is there a .NET equivalent function of C atoi?

If I have a line like:

"26 things" 

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

If I used C, I would just use the atoi function. But I can not find anything equivalent in .NET.

What is the easiest way to capture an integer from the beginning of a line?

Edit: Sorry I was ambiguous. Answers looking for a space in a line will work in many cases (maybe even mine). I was hoping for the atoi equivalent in .NET. The answer should also work with a string like "26things". Thanks.

+4
source share
10 answers

This should work (edited to ignore the white space at the beginning of the line)

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

If you are worried about checking for a value, you can do the following to give you a value of -1 if there is no integer at the beginning of the line.

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

It looks very pretty:

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

And, a boring solution for those who really want atoi:

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

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

+2
source

one way would be

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

The direct equivalent is int.Parse (string), but I'm not quite sure if it only takes the start number.

0
source

You can call Val in the Microsoft.VisualBasic.Conversion namespace. In your script, it should print "26". I don't know if this is 100% compatible in toher scripts. Here is a link to the specification.

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

0
source

If you want only an integer

 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; } 
0
source

Try the following:

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

I can only think 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 him:

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

You need to split the string and then parse it:

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

All Articles