Introduction
Removing whitespace from a string involves eliminating all spaces, tabs, and other whitespace characters from the string. This operation is common in data cleaning and text processing. This guide will demonstrate how to write a Go program that removes all whitespace from a given string.
Problem Statement
Create a Go program that:
- Prompts the user to enter a string.
- Removes all whitespace characters from the string.
- Displays the modified string.
Example:
- Input:
"Hello, World! Welcome to Go." - Output:
"Hello,World!WelcometoGo."
Solution Steps
- Import the fmt and strings Packages: Use
import "fmt"for formatted I/O operations andimport "strings"for string manipulation functions. - 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. - Remove Whitespace: Use the
strings.ReplaceAllfunction to remove all spaces by replacing them with an empty string. - Display the Modified String: Use
fmt.Printlnto display the modified string.
Go Program
package main
import (
"fmt"
"strings"
)
/**
* Go Program to Remove Whitespace from a String
* 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: Remove all whitespace by replacing spaces with an empty string
modifiedString := strings.ReplaceAll(input, " ", "")
// Step 4: Display the modified string
fmt.Println("String without whitespace:", modifiedString)
}
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: Remove Whitespace
- The
strings.ReplaceAllfunction is used to replace all occurrences of a space character (" ") with an empty string (""). This effectively removes all spaces from the input string.
Step 4: Display the Modified String
- The program prints the modified string, which has no spaces, using
fmt.Println.
Output Example
Example 1:
Enter a string: Hello, World! Welcome to Go.
String without whitespace: Hello,World!WelcometoGo.
Example 2:
Enter a string: Go is a powerful language
String without whitespace: Goisapowerfullanguage
Conclusion
This Go program demonstrates how to remove all whitespace from a string using the strings.ReplaceAll function. It covers basic programming concepts such as string manipulation, input/output operations, and handling user input. This example is useful for beginners learning Go programming and understanding how to clean and manipulate strings.