Val
Val

Reputation: 57

How do I check if each of the characters in my string, is just one specific letter?

How do I check if my whole string is nothing but one letter for each of the character positions? For example, I want to check that the string variable "Word1" only contains "_" (underscores).

Lets say Word1 = "____"; How can the program check to make sure there are no letters just underscores in that variable?

Upvotes: 0

Views: 106

Answers (3)

Tinwor
Tinwor

Reputation: 7983

Linq All is the cleanest way but you can also use regex for this task.
Something like: ^(_+)$ will match only if there is one or more _

    Regex regex = new Regex(@"^(_+)$");
    if (match.IsMatch(myString))
        Console.WriteLine("Matched");

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

Use Linq All:

char charToTest = '_';
var result = myString.All(x => x == charToTest);

Returns true only if the charToTest was found on any position. Furthermore when any position has another character the statement immedialtly returns false without checking for further positions.

EDIT: As @CSharpie pointed out this will also return true if your string is empty. To avoid this check for String.IsNullOrEmpty before:

var result = !String.IsNullOrEmpty(myString) && myString.All(x => x == charToTest);

Upvotes: 5

J.R.
J.R.

Reputation: 167

You can do it with Linq (using System.Linq)

if (Word1.All(c => c == '_'))
{
    // only underscores
}

Upvotes: 1

Related Questions