Go Program to Convert a String to Uppercase

Introduction

Converting a string to uppercase involves changing all the lowercase letters in the string to their corresponding uppercase 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 uppercase.

Problem Statement

Create a Go program that:

  • Prompts the user to enter a string.
  • Converts the string to uppercase.
  • Displays the uppercase 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 Uppercase: Use the strings.ToUpper function to convert the string to uppercase.
  5. Display the Uppercase String: Use fmt.Println to display the uppercase string.

Go Program

package main

import (
    "fmt"
    "strings"
)

/**
 * Go Program to Convert a String to Uppercase
 * 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 uppercase using the strings.ToUpper function
    uppercase := strings.ToUpper(input)

    // Step 4: Display the uppercase string
    fmt.Println("Uppercase string:", uppercase)
}

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 Uppercase

  • The strings.ToUpper function is used to convert the input string to uppercase. This function changes all lowercase letters to their corresponding uppercase letters and leaves other characters unchanged.

Step 4: Display the Uppercase String

  • The program prints the uppercase string using fmt.Println.

Output Example

Example 1:

Enter a string: Hello, World!
Uppercase string: HELLO, WORLD!

Example 2:

Enter a string: goLang is fun
Uppercase string: GOLANG IS FUN

Conclusion

This Go program demonstrates how to convert a string to uppercase using the strings.ToUpper 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