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

One solution is to use strings.ToUpper()/ToLower() and compare with the original string. This works for the punctuation case as well.

Here's the solution:

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "UPPERCASE"
    fmt.Println(strings.ToUpper(s) == s)

    s = "lowercase"
    fmt.Println(strings.ToUpper(s) == s)

    s = "lowercase"
    fmt.Println(strings.ToLower(s) == s)

    s = "I'M YELLING AT YOU!"
    fmt.Println(strings.ToUpper(s) == s)
}

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
}