Write a Go program to perform string concatenation. In this example program, we declared two strings and used an arithmetic operator to concat them.
package main
import (
"fmt"
)
func main() {
str1 := "Hello "
str2 := "World"
str3 := str1 + str2
fmt.Println(str3)
}
Hello World
This program allows users to enter two different strings and concat them.
package main
import "fmt"
func main() {
var str1 string
fmt.Print("Enter the First String to Concat = ")
fmt.Scanln(&str1)
var str2 string
fmt.Print("Enter the Second String to Concat = ")
fmt.Scanln(&str2)
str3 := str1 + str2
fmt.Println(str3)
}
Enter the First String to Concat = Tutorial
Enter the Second String to Concat = Gateway
TutorialGateway
The above concatenation example works with one-word strings. We have to use this example to read the multi-word string user input. This example accepts two strings and concat them using the + operator.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the First String to Concat = ")
str1, _ := reader.ReadString('\n')
str1 = strings.TrimSuffix(str1, "\n")
fmt.Print("Enter the Second String to Concat = ")
str2, _ := reader.ReadString('\n')
str2 = strings.TrimSuffix(str2, "\n")
str3 := str1 + " " + str2
fmt.Println(str3)
}
