KlappDaddy
KlappDaddy

Reputation: 27

Checking if a string contains an int

public static void nameAsk()
    {
        bool check = true;

        while (check)
        {
            Console.WriteLine("What is your name?");
            string name = Console.ReadLine();
            int userName;

            bool checkIfInt = int.TryParse(name, out userName);

            if (checkIfInt)
            {
                Console.WriteLine("Welcome " + name + "!");
                break;
            }
            else
            {
                Console.WriteLine("Please enter a name without numbers");
            }
        }
    }

I am attempting to check if the name contains an int, but no matter what I do, I can't seem to get the output I am looking for.

I have entered the following 3 outputs and these are the results I get:

[Input: "John2" | Output: "Please enter a name without numbers"]

[Input: "John" | Output: "Please enter a name without numbers"]

[Input: 9 | Output: "Welcome 9!"]

Fixed by changing bool checkIfInt = name.Any(Char.IsDigit), I then put it into my if statement, but set it to false, as follows:

bool checkIfInt = name.Any(Char.IsDigit);

if (!checkIfInt)
{
  Console.WriteLine("Welcome " + name + "!");
  break;
}
else
{
   Console.WriteLine("Please enter a name without numbers");
}
}

Upvotes: 2

Views: 5353

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

int.ParseInt will pass only when name is an int, and has no other characters.

You can check if a string contains a number anywhere in it with LINQ using Any:

if (name.Any(Char.IsDigit)) {
    ...
}

Upvotes: 7

Related Questions