Go Program to Convert a String to Lowercase

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

  1. Import the fmt and strings Packages: Use import "fmt" and import "strings" to include the fmt package for formatted I/O operations and the strings package for string manipulation.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Input the String: Use fmt.Scanln or fmt.Scanf to take input from the user for the string.
  4. Convert the String to Lowercase: Use the strings.ToLower function to convert the string to lowercase.
  5. Display the Lowercase String: Use fmt.Println to 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 input is 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. The fmt.Scanln function reads the input and stores it in the input variable.

Step 3: Convert the String to Lowercase

  • The strings.ToLower function 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top