Search code examples
stringgouppercaselowercase

How to check if a string is all upper or lower case in Go?


What is an easy way in Golang to check if all characters in a string are upper case or lower case?

Also, how to handle a case where the string has punctuation?

See these examples:

package main

import (
    "fmt"
    "unicode"
)

func main() {
    s := "UPPERCASE"
    fmt.Println(s.IsUpper())  // Should print true

    s = "lowercase"
    fmt.Println(s.IsUpper())  // Should print false

    s = "lowercase"
    fmt.Println(s.IsLower())  // Should print true

    s = "I'M YELLING AT YOU!"
    fmt.Println(s.IsUpper())  // Should print true
}

Note: s.IsUpper() and s.IsLower() doesn't really exist, but would be nice to find an equivalent.


Solution

  • You can of course compare the upper and lower cased strings in their entirety, or you can short-circuit the comparisons on the first failure, which would be more efficient when comparing long strings.

    func IsUpper(s string) bool {
        for _, r := range s {
            if !unicode.IsUpper(r) && unicode.IsLetter(r) {
                return false
            }
        }
        return true
    }
    
    func IsLower(s string) bool {
        for _, r := range s {
            if !unicode.IsLower(r) && unicode.IsLetter(r) {
                return false
            }
        }
        return true
    }