How to check if a string is title case in VB.NET

1 Answer

0 votes
Imports System

Module TitleCaseCheck

    Function IsTitleCase(s As String) As Boolean
        Dim newWord As Boolean = True

        For Each c As Char In s
            If Char.IsWhiteSpace(c) Then
                newWord = True
            Else
                If newWord Then
                    If Not Char.IsUpper(c) Then
                        Return False
                    End If
                    newWord = False
                Else
                    If Not Char.IsLower(c) Then
                        Return False
                    End If
                End If
            End If
        Next

        Return True
    End Function

    Sub Main()
        Dim tests() As String = {
            "Hello World",
            "Hello world",
            "hello World",
            "Visual Basic Language",
            "This Is Fine",
            "This is Not Fine"
        }

        For Each t In tests
            Console.WriteLine($"""{t}"" -> {IsTitleCase(t)}")
        Next
    End Sub

End Module



' run:
' 
' "Hello World" -> True
' "Hello world" -> False
' "hello World" -> False
' "Visual Basic Language" -> True
' "This Is Fine" -> True
' "This is Not Fine" -> False
' 

 



answered 3 hours ago by avibootz
...