Check If the Rune is a Lowercase Letter or not in Golang


A Unicode code point is represented by the rune type in Go. For many string operations, including case conversion, counting the number of lowercase letters in a string, and other string operations, it is helpful to know if a rune is an uppercase letter or lowercase letter. The several approaches to determine if a rune in Go is a lowercase letter or not will be covered in this article.

Using the Unicode Package

Go's unicode package offers a number of functions for working with Unicode characters. One such function is IsLower, which gives a true result if the given rune is a lowercase letter and a false result otherwise.

Example

package main

import (
   "fmt"
   "unicode"
)

func main() {
   r := 'a'
   if unicode.IsLower(r) {
      fmt.Println("The rune is a lowercase letter")
   } else {
      fmt.Println("The rune is not a lowercase letter")
   }
}

Output

The rune is a lowercase letter

In the above example, we check if the rune r is a lowercase letter or not using the unicode.IsLower function.

Using ASCII Range

In ASCII, the lowercase letters are represented by the integers between 97 and 122. We can use this fact to check whether a rune is a lowercase letter or not.

Example

package main

import "fmt"

func main() {
   r := 'a'
   if r >= 'a' && r <= 'z' {
      fmt.Println("The rune is a lowercase letter")
   } else {
      fmt.Println("The rune is not a lowercase letter")
   }
}

Output

The rune is a lowercase letter

In the above example, we check whether the rune r is a lowercase letter or not by checking if its ASCII value is between 97 and 122.

Using Switch Case

We can also use the switch statement in Go to check whether a rune is a lowercase letter or not.

Example

package main

import "fmt"

func main() {
   r := 'a'
   switch {
   case r >= 'a' && r <= 'z':
      fmt.Println("The rune is a lowercase letter")
   default:
      fmt.Println("The rune is not a lowercase letter")
   }
}

Output

The rune is a lowercase letter

In the above example, we use a switch statement to check whether the rune r is a lowercase letter or not. We use the case statement with the condition r >= 'a' && r <= 'z' to check if the rune is a lowercase letter.

Conclusion

In this article, we looked at a few different techniques to determine in Go if a rune is a lowercase letter or not. We have seen how to determine whether a rune is a lowercase letter or not using the switch statement, the ASCII range, and the unicode package. It is important to choose the method that is most appropriate for your unique use case.

Updated on: 07-Apr-2023

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements