Introduction
Converting a string to lowercase involves changing all the uppercase letters in the string to their corresponding lowercase letters. This is a common task in text processing. This guide will demonstrate how to write a Go program that converts a given string to lowercase.
Problem Statement
Create a Go program that:
- Prompts the user to enter a string.
- Converts the string to lowercase.
- Displays the lowercase string.
Example:
- Input: "Hello, World!"
- Output: "hello, world!"
Solution Steps
- Import the fmt and strings Packages: Use import "fmt"andimport "strings"to include the fmt package for formatted I/O operations and the strings package for string manipulation.
- Write the Main Function: Define the mainfunction, which is the entry point of every Go program.
- Input the String: Use fmt.Scanlnorfmt.Scanfto take input from the user for the string.
- Convert the String to Lowercase: Use the strings.ToLowerfunction to convert the string to lowercase.
- Display the Lowercase String: Use fmt.Printlnto display the lowercase string.
Go Program
package main
import (
    "fmt"
    "strings"
)
/**
 * Go Program to Convert a String to Lowercase
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare a variable to hold the input string
    var input string
    // Step 2: Prompt the user to enter a string
    fmt.Print("Enter a string: ")
    fmt.Scanln(&input)
    // Step 3: Convert the string to lowercase using the strings.ToLower function
    lowercase := strings.ToLower(input)
    // Step 4: Display the lowercase string
    fmt.Println("Lowercase string:", lowercase)
}
Explanation
Step 1: Declare Variables
- The variable inputis declared to store the user’s input string.
Step 2: Input the String
- The program prompts the user to enter a string using fmt.Print. Thefmt.Scanlnfunction reads the input and stores it in theinputvariable.
Step 3: Convert the String to Lowercase
- The strings.ToLowerfunction is used to convert the input string to lowercase. This function changes all uppercase letters to their corresponding lowercase letters and leaves other characters unchanged.
Step 4: Display the Lowercase String
- The program prints the lowercase string using fmt.Println.
Output Example
Example 1:
Enter a string: Hello, World!
Lowercase string: hello, world!
Example 2:
Enter a string: GoLang Is Fun
Lowercase string: golang is fun
Conclusion
This Go program demonstrates how to convert a string to lowercase using the strings.ToLower function. It covers basic programming concepts such as string manipulation and input/output operations. This example is useful for beginners learning Go programming and understanding how to work with strings and modify their content.