How to convert a slice of bytes in lowercase in Golang?


In Golang, a byte slice is a sequence of bytes. A slice of bytes can be created using the built-in function []byte(). Sometimes, you may want to convert a slice of bytes to lowercase. This can be easily achieved using the bytes.ToLower() function. In this article, we will learn how to convert a slice of bytes to lowercase in Golang.

Using bytes.ToLower()

The bytes.ToLower() function converts a slice of bytes to lowercase. Here's how to use it −

Example

package main

import (
   "bytes"
   "fmt"
)

func main() {
   s := []byte("GOlang")
   fmt.Println("Original:", string(s)) // Output: Original: GOlang
   s = bytes.ToLower(s)
   fmt.Println("Lowercase:", string(s)) // Output: Lowercase: golang
}

Output

Original: GOlang
Lowercase: golang

In this example, we create a slice of bytes s with the value "GOlang". We then use the bytes.ToLower() function to convert the slice to lowercase. The function returns a new slice with all the bytes in lowercase, and we assign this new slice back to s. Finally, we print the original and lowercase versions of the slice using the fmt.Println() function.

Using For Loop

If you prefer to convert a slice of bytes to lowercase without using the bytes.ToLower() function, you can use a for loop and the unicode.ToLower() function. Here's an example −

Example

package main

import (
   "fmt"
   "unicode"
)

func main() {
   s := []byte("GOlang")
   fmt.Println("Original:", string(s)) // Output: Original: GOlang
   for i, b := range s {
      s[i] = byte(unicode.ToLower(rune(b)))
   }
   fmt.Println("Lowercase:", string(s)) // Output: Lowercase: golang
}

Output

Original: GOlang
Lowercase: golang

In this example, we create a slice of bytes s with the value "GOlang". We then use a for loop to iterate over each byte in the slice. For each byte, we convert it to a rune using the rune() function and then call the unicode.ToLower() function to convert it to lowercase. Finally, we convert the rune back to a byte and assign it back to the slice. Finally, we print the original and lowercase versions of the slice using the fmt.Println() function.

Conclusion

In this article, we learned how to convert a slice of bytes to lowercase in Golang using the bytes.ToLower() function and a for loop with the unicode.ToLower() function. The bytes.ToLower() function is the recommended way to convert a slice of bytes to lowercase as it is more concise and efficient.

Updated on: 20-Apr-2023

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements