Home > Software engineering >  How to check if comma separated string contains only numbers?
How to check if comma separated string contains only numbers?

Time:07-30

I want to pass input as numbers separated by a comma (,) in a method which return true or false. The method DoesInputContainsNumbers should return true if all are numbers and return false if any of them are non numbers. For example, the input "20, 10, 30, 40" return true while the input "10, 20,aaa" return false. Is there a better way to achieve this than the below I tried?

public static bool DoesInputContainsNumbers(string input)
{
    if (string.IsNullOrWhiteSpace(input))
    {
        return false;
    }
    try
    {
        input.Split(",").Select(x => int.Parse(x)).ToList();
    }
    catch (Exception ex)
    {
        return false;
    }
    return true;
}

CodePudding user response:

Yes - rather than catching an exception, use int.TryParse, which already return a bool. You can then simplify it to:

public static bool DoesInputContainsNumbers(string input) =>
    !string.IsNullOrWhiteSpace(input) &&
    input.Split(',').All(x => int.TryParse(x, out _));

CodePudding user response:

Follow below code ,it will solve your issue.

public static bool DoesInputContainsNumbers(string input){
    !string.IsNullOrWhiteSpace(input) && 
    !str.Split(',').Any(x=>{ int val;return !int.TryParse(x,out val); });
    }
  •  Tags:  
  • c#
  • Related