Open In App

How to convert a string in lower case in Golang?

Last Updated : 12 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Go, converting a string to lowercase is a common operation that can be accomplished easily using the strings package. This package provides various string manipulation functions, including the ToLower function, which converts all Unicode characters in a string to their lowercase equivalent.

Example

Input: Hello, Geeks!
Output: hello, geeks!
Explanation: The ToLower function in Go converts all Unicode characters in a string to their lowercase equivalent, returning a new string.

Syntax

The syntax of the ToLower function is as follows:

lowerS := strings.ToLower(s)

Where:

  • s is the original string you want to convert to lowercase.
  • lowerS is the new string with all characters converted to lowercase.

Convert a String to Lower Case

In Go, converting a string to lowercase is a common operation that can be accomplished easily using the ToLower function.

Syntax

The syntax of the ToLower function is as follows:

lowerS := strings.ToLower(s)

Example

Go
package main
import (
    "fmt"
    "strings"
)
func main() {
    // Initial string
    s := "Hello, Geeks!"
    fmt.Println("", s)

    // Converting to lower case
    lowerS := strings.ToLower(s)
    fmt.Println("", lowerS)
}

Output
 Hello, Geeks!
 hello, geeks!

Converting Multiple Strings

You can also convert multiple strings to lower case by using a loop.

Syntax

for i, s := range phrases {
phrases[i] = strings.ToLower(s)
}

Where:

  • phrases is a slice of strings that you want to convert to lower case.

Example

Go
package main
import (
    "fmt"
    "strings"
)
func main() {
    // Initial strings
    phrases := []string{"Hello, Geeks!", "GoLang is Fun!"}
    
    fmt.Println("", phrases)
    
    // Converting to lower case
    for i, s := range phrases {
        phrases[i] = strings.ToLower(s)
    }
    
    fmt.Println("", phrases)
}

Output
 [Hello, Geeks! GoLang is Fun!]
 [hello, geeks! golang is fun!]

Handling User Input

You can also convert user input to lower case.

Syntax

fmt.Scanln(&userInput)
lowerInput := strings.ToLower(userInput)

Where:

  • userInput captures the string entered by the user.

Example

Go
package main
import (
    "fmt"
    "strings"
)

func main() {
    // User input
    var userInput string
    fmt.Print("Enter string: ")
    fmt.Scanln(&userInput)

    // Converting to lower case
    lowerInput := strings.ToLower(userInput)
    fmt.Println("Lower case input:", lowerInput)
}

Output
Enter string: Lower case input: 

Conclusion

Converting a string to lower case in Go is straightforward using the strings.ToLower function. Whether working with a single string, multiple strings, or user input, the process remains simple and efficient.




Next Article

Similar Reads

three90RightbarBannerImg
  翻译: