How to check if a string is title case in C#

1 Answer

0 votes
using System;

class TitleCaseCheck
{
    public static bool IsTitleCase(string s) {
        bool newWord = true;

        foreach (char c in s) {
            if (char.IsWhiteSpace(c)) {
                newWord = true;
            }
            else {
                if (newWord) {
                    if (!char.IsUpper(c))
                        return false;

                    newWord = false;
                }
                else {
                    if (!char.IsLower(c))
                        return false;
                }
            }
        }

        return true;
    }

    static void Main()
    {
        string[] tests = {
            "Hello World",
            "Hello world",
            "hello World",
            "C Sharp Language",
            "This Is Fine",
            "This is Not Fine"
        };

        foreach (string t in tests) {
            Console.WriteLine($"\"{t}\" -> {IsTitleCase(t)}");
        }
    }
}


/*
run:

"Hello World" -> True
"Hello world" -> False
"hello World" -> False
"C Sharp Language" -> True
"This Is Fine" -> True
"This is Not Fine" -> False

*/

 



answered 4 hours ago by avibootz
...