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
- 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 Uppercase: Use the strings.ToUpperfunction to convert the string to uppercase.
- Display the Uppercase String: Use fmt.Printlnto 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 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 Uppercase
- The strings.ToUpperfunction 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.