In C#, how to check whether a string contains an integer?

C#StringParsingIntegerTryparse

C# Problem Overview


I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.

Currently I am doing:

int parsedId;
if (
    (String.IsNullOrEmpty(myStringVariable) ||
    (!uint.TryParse(myStringVariable, out parsedId))
)
{//..show error message}

This is ugly - How to be more concise?

Note: I know about extension methods, but I wonder if there is something built-in.

C# Solutions


Solution 1 - C#

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit)

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit)

Will return true if the string contains a digit

Solution 2 - C#

Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:

bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);

Solution 3 - C#

Maybe this can help

string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));

answer from msdn.

Solution 4 - C#

You can check if string contains numbers only:

Regex.IsMatch(myStringVariable, @"^-?\d+$")

But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

Another option - create extension method and move ugly code there:

public static bool IsInteger(this string s)
{
   if (String.IsNullOrEmpty(s))
       return false;

   int i;
   return Int32.TryParse(s, out i);
}

That will make your code more clean:

if (myStringVariable.IsInteger())
    // ...

Solution 5 - C#

This work for me.

("your string goes here").All(char.IsDigit)

Solution 6 - C#

Sorry, didn't quite get your question. So something like this?

str.ToCharArray().Any(char.IsDigit);

Or does the value have to be an integer completely, without any additional strings?

if(str.ToCharArray().All(char.IsDigit(c));

Solution 7 - C#

The answer seems to be just no.

Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).

Solution 8 - C#

        string text = Console.ReadLine();
        bool isNumber = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (char.IsDigit(text[i]))
            {
                isNumber = true;
                break;
            }
        }

        if (isNumber)
        {
            Console.WriteLine("Text contains number.");
        }
        else
        {
            Console.WriteLine("Text doesn't contain number.");
        }

        Console.ReadKey();

Or Linq:

        string text = Console.ReadLine();

        bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
        Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
        Console.ReadKey();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcelView Question on Stackoverflow
Solution 1 - C#DGibbsView Answer on Stackoverflow
Solution 2 - C#dtbView Answer on Stackoverflow
Solution 3 - C#panakoView Answer on Stackoverflow
Solution 4 - C#Sergey BerezovskiyView Answer on Stackoverflow
Solution 5 - C#sarmad salikView Answer on Stackoverflow
Solution 6 - C#SBossView Answer on Stackoverflow
Solution 7 - C#MarcelView Answer on Stackoverflow
Solution 8 - C#ZsoltView Answer on Stackoverflow