C# check to see if an input contains only lowercas

2019-09-08 02:07发布

问题:

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

回答1:

Without regex, youu 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.



回答2:

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


回答3:

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
    }
}