Home > Software engineering >  Using .Split to Split a string and return first integer values
Using .Split to Split a string and return first integer values

Time:10-27

Been trying to take a string and split it using a space and get the first integer from the string. The integer has to be on its own, so no other characters in it. Any help appreciated

CodePudding user response:

Maybe

string input = "sdf fg gfh 4v 345gg g 4 dfg dfg";

int? result  = input.Split(' ')
   .Select(x => int.TryParse(x, out int val) ? val : (int?)null)
   .FirstOrDefault(x => x != null);

Console.WriteLine(result);

Output

4

CodePudding user response:

Try this:

var firstOrDefaultInteger = input.Split(' ')
    .FirstOrDefault(x => int.TryParse(x, out _));

CodePudding user response:

You can try Linq in order to query the source string:

 string source = "abc a5 123 789 pqr";

 string result = source
   .Split(' ')
   .FirstOrDefault(item => item.Any() && item.All(c => c >= '0' && c <= '9'));

Here we split source into

 {"abc", "a5", "123", "789", "pqr"}

and then get "123" - first not empty item which contains digits only.

Edit: Note, that, result is of type string, since not any sequence of digits is a valid int: e.g. 123456789123456789 is too long for int. If we can guarantee that result is short enough, then you can parse it into some itenteger type, e.g.

int answer = int.Parse(result);

or

long answer = long.Parse(result);

or even

BigInteger answer = BigInteger.Parse(result);

If we accept negative values as well, we can put regular expression:

using System.Text.RegularExpressions;

...

string result = source
  .Split(' ')
  .FirstOrDefault(item => Regex.IsMatch(item, @"^\-?[0-9] $"));
  •  Tags:  
  • c#
  • Related