Ellie
Ellie

Reputation: 33

C# check to see if an input contains only lowercase letters a-z

I'm stuck on a task of trying to print words that contain only lowercase letters a-z. I have already stripped out an inputted string if it contains any number 0-9 and if it contains an Uppercase letter:

    String[] textParts;
    textParts = text.Split(delimChars);
    for (int i = 0; i < textParts.Length; i++)  //adds s to words list and checks for capitals
    {
        String s = textParts[i];
        bool valid = true;

        foreach (char c in textParts[i])
        {
            if (char.IsUpper(c))
            {
                valid = false;
                break;
            }

            if (c >= '0' && c <= '9')
            {
                valid = false;
                break;
            }

            if (char.IsPunctuation(c))
            {
                valid = false;
                break;
            }

        }
        if (valid) pageIn.words.Add(s);

This is my code so far. The last part I'm trying to check to see if a word contains any punctuation (it's not working) is there an easier way I could do this and how could I get the last part of my code to work?

P.S. I'm not that comfortable with using Regex.

Many Thanks, Ellie

Upvotes: 2

Views: 4716

Answers (3)

cdie
cdie

Reputation: 4544

Without regex, you can use LINQ (might be less performant)

bool isOnlyLower = s.Count(c => Char.IsLower(c)) == s.Length;

Count will retrieve the number of char that are in lower in the following string. If it match the string's length, string is composed only of lowercase letters.

An alternative would be to check if there's any UpperCase :

bool isOnlyLower = !s.Any(c => Char.IsUpper(c));

Upvotes: 3

Crypth
Crypth

Reputation: 1642

var regex = new Regex("^[a-z]+$");
if (!regex.IsMatch(input))
{
            // is't not only lower case letters, remove input
}

Upvotes: 1

Edi G.
Edi G.

Reputation: 2420

I'm not sure whether I get your question right, but shouldn't the following work?

for (int i = 0; i < textParts.Length; i++)  //adds s to words list and checks for capitals
{
    String s = textParts[i];

    if(s.Equals(s.ToLower()))
    {
        // string is all lower
    }
}

Upvotes: -1

Related Questions