C# check to see if an input contains only lowercas

2019-09-08 02:00发布

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-08 02:18

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.

查看更多
甜甜的少女心
3楼-- · 2019-09-08 02:29

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
    }
}
查看更多
戒情不戒烟
4楼-- · 2019-09-08 02:33
var regex = new Regex("^[a-z]+$");
if (!regex.IsMatch(input))
{
            // is't not only lower case letters, remove input
}
查看更多
登录 后发表回答