Go Program to Convert String to Lowercase
In Go, you can convert a string to lowercase using the
strings.ToLower function from the strings package like this: lower := strings.ToLower(yourString).Examples
InputHELLO
Outputhello
InputGoLang
Outputgolang
Input123ABC!@#
Output123abc!@#
How to Think About It
To convert a string to lowercase in Go, think of it as changing all uppercase letters to their lowercase versions while leaving other characters unchanged. The
strings package provides a ready-made function ToLower that handles this for you, so you just pass your string to it and get the lowercase result.Algorithm
1
Import the strings package.2
Get the input string you want to convert.3
Call the strings.ToLower function with the input string.4
Store or use the returned lowercase string.Code
go
package main import ( "fmt" "strings" ) func main() { input := "Hello, GoLang!" lower := strings.ToLower(input) fmt.Println(lower) }
Output
hello, golang!
Dry Run
Let's trace the string "Hello, GoLang!" through the code
1
Input string
input = "Hello, GoLang!"
2
Convert to lowercase
lower = strings.ToLower(input) // lower = "hello, golang!"
3
Print result
Output: hello, golang!
| Step | Input | Output |
|---|---|---|
| 1 | Hello, GoLang! | |
| 2 | Hello, GoLang! | hello, golang! |
| 3 | hello, golang! |
Why This Works
Step 1: Import strings package
The strings package contains useful functions for string manipulation, including ToLower.
Step 2: Use strings.ToLower
Calling strings.ToLower on a string returns a new string with all uppercase letters converted to lowercase.
Step 3: Print the result
The converted lowercase string is printed to the console using fmt.Println.
Alternative Approaches
Manual conversion using rune iteration
go
package main import ( "fmt" ) func toLowerManual(s string) string { result := []rune{} for _, r := range s { if r >= 'A' && r <= 'Z' { r += 'a' - 'A' } result = append(result, r) } return string(result) } func main() { input := "Hello, GoLang!" fmt.Println(toLowerManual(input)) }
This method manually converts uppercase letters to lowercase by checking rune values. It is less efficient and more complex than using strings.ToLower.
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each character once, so the time grows linearly with the string length.
Space Complexity
A new string is created for the lowercase result, so space usage is proportional to the input size.
Which Approach is Fastest?
Using strings.ToLower is optimized and faster than manual rune conversion, and it handles Unicode correctly.
| Approach | Time | Space | Best For |
|---|---|---|---|
| strings.ToLower | O(n) | O(n) | Simple, reliable lowercase conversion |
| Manual rune iteration | O(n) | O(n) | Learning purpose, custom logic |
Always use strings.ToLower for simple and reliable lowercase conversion in Go.
Forgetting to import the strings package causes a compilation error when using strings.ToLower.