×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.Join() Function with Examples

Golang | strings.Join() Function: Here, we are going to learn about the Join() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 17, 2021

strings.Join()

The Join() function is an inbuilt function of strings package which is used to join (concatenate) the slices of strings (elements of the first parameter) with the given separator to create a single string. It accepts two parameters – slices of strings and a separator and returns a concatenated string with the separator.

Syntax

func Join(strs []string, sep string) string

Parameters

  • strs : Slices of the strings (multiple strings) to concatenate
  • sep : Separator

Return Value

The return type of Join() function is a string, it returns a concatenated string with the separator.

Example 1

// Golang program to demonstrate the
// example of strings.Join() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str []string

	str = []string{"Nehru Place", "New Delhi", "India"}
	fmt.Println(strings.Join(str, ", "))

	str = []string{"New Delhi", "Mumbai", "Indore"}
	fmt.Println(strings.Join(str, "***"))
}

Output:

Nehru Place, New Delhi, India
New Delhi***Mumbai***Indore

Example 2

// Golang program to demonstrate the
// example of strings.Join() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str []string
	var sep string
	var final_string string

	str = []string{"Nehru Place", "New Delhi", "India"}
	sep = ", "
	final_string = strings.Join(str, sep)
	fmt.Printf("Strings: %q\nSeparator: %q\nConcatenated string: %q\n", str, sep, final_string)

	str = []string{"Delhi", "Indore", "Mumbai"}
	sep = "-"
	final_string = strings.Join(str, sep)
	fmt.Printf("Strings: %q\nSeparator: %q\nConcatenated string: %q\n", str, sep, final_string)

	str = []string{"Hello, world!", "Hi there?", "I'm fine"}
	sep = "###"
	final_string = strings.Join(str, sep)
	fmt.Printf("Strings: %q\nSeparator: %q\nConcatenated string: %q\n", str, sep, final_string)
}

Output:

Strings: ["Nehru Place" "New Delhi" "India"]
Separator: ", "
Concatenated string: "Nehru Place, New Delhi, India"
Strings: ["Delhi" "Indore" "Mumbai"]
Separator: "-"
Concatenated string: "Delhi-Indore-Mumbai"
Strings: ["Hello, world!" "Hi there?" "I'm fine"]
Separator: "###"
Concatenated string: "Hello, world!###Hi there?###I'm fine"

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.