Different ways to concatenate two strings in Golang
In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator.
New string 1: Welcome!GeeksforGeeks New string 2: GeeksforGeeks
Other Methods for concatenating strings
- Using bytes.Buffer: You can also create a string by concatenating the bytes of the strings using bytes.Buffer with WriteString() method. It is defined under bytes package. It prevents the generation of the unnecessary string object, means it doesn’t generate a new string like in + operator from two or more strings. Example:
String: Geeks String: GeeksforGeeks
- Using Sprintf: In Go language, you can also concatenate string using Sprintf() method. Example:
- Using += operator or String append: In Go strings, you are allowed to append a string using += operator. This operator adds a new or given string to the end of the specified string. Example:
String: WelcomeGeeksforGeeks String: WelcomeGeeksforGeeksThis is the tutorial of Go language String: GeeksforGeeksPortal
- Using Join() function: This function concatenates all the elements present in the slice of string into a single string. This function is available in string package. Syntax:
func Join(str string, sep string) string
- Here, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string. Example:
- Using strings.Builder: You can also create a string by concatenating the strings using strings.Builder with WriteString() method. It is defined under strings package. It uses less memory while concatenating strings and is a better way of concatenation. The function WriteString appends the contents of the string to a buffer and allows us to concatenate strings in a faster way. It prevents the generation of the unnecessary string object, means it doesn’t generate a new string like in + operator from two or more strings.
String: Welcome String: Welcome to GeeksforGeeks!
My Personal Notes arrow_drop_up
Please Login to comment...