Introduction
String concatenation is the process of combining two or more strings into a single string. This is a common operation in programming, often used to build messages, combine data, or format output. This guide will demonstrate how to write a Go program that concatenates two strings.
Problem Statement
Create a Go program that:
- Prompts the user to enter two strings.
- Concatenates the two strings.
- Displays the concatenated string.
Example:
- Input:
- String 1:
"Hello, " - String 2:
"World!"
- String 1:
- Output:
"Hello, World!"
Solution Steps
- Import the fmt Package: Use
import "fmt"to include the fmt package for formatted I/O operations. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Input the Strings: Use
fmt.Scanlnorfmt.Scanfto take input from the user for the two strings. - Concatenate the Strings: Use the
+operator to concatenate the two strings. - Display the Concatenated String: Use
fmt.Printlnto display the concatenated string.
Go Program
package main
import "fmt"
/**
* Go Program to Concatenate Two Strings
* Author: https://www.javaguides.net/
*/
func main() {
// Step 1: Declare variables to hold the input strings
var str1, str2 string
// Step 2: Prompt the user to enter the first string
fmt.Print("Enter the first string: ")
fmt.Scanln(&str1)
// Step 3: Prompt the user to enter the second string
fmt.Print("Enter the second string: ")
fmt.Scanln(&str2)
// Step 4: Concatenate the strings using the + operator
concatenatedString := str1 + str2
// Step 5: Display the concatenated string
fmt.Println("Concatenated string:", concatenatedString)
}
Explanation
Step 1: Declare Variables
- The variables
str1andstr2are declared to store the user’s input strings.
Step 2: Input the First String
- The program prompts the user to enter the first string using
fmt.Print. Thefmt.Scanlnfunction reads the input and stores it in thestr1variable.
Step 3: Input the Second String
- The program prompts the user to enter the second string in a similar way, storing the input in the
str2variable.
Step 4: Concatenate the Strings
- The
+operator is used to concatenatestr1andstr2, forming a new string stored in the variableconcatenatedString.
Step 5: Display the Concatenated String
- The program prints the concatenated string using
fmt.Println.
Output Example
Example 1:
Enter the first string: Hello,
Enter the second string: World!
Concatenated string: Hello, World!
Example 2:
Enter the first string: GoLang
Enter the second string: is awesome!
Concatenated string: GoLang is awesome!
Conclusion
This Go program demonstrates how to concatenate two strings using the + operator. 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 combine them.