Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Join a string by delimiter or a separator in Go (Golang)

Posted on March 11, 2023March 11, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a Join method that can be used to join a string based upon a delimiter.

Below is the signature of the function

func Join(a []string, sep string)

As you can notice this function takes a slice of string and a delimiter and it returns a combined string joined by a delimiter. The delimiter or separator is placed between elements of the input string slice. Please note

  • It will return an empty string if the length of the input slice is zero
  • It will output a string combined from the slice of strings if the input delimiter or separator is empty.

Let’s look at the working code

Code:

package main
import (
"fmt"
"strings"
)
func main() {
//Case 1 s contains sep. Will output slice of length 3
res := strings.Join([]string{"ab", "cd", "ef"}, "-")
fmt.Println(res)
//Case 2 slice is empty. It will output a empty string
res = strings.Join([]string{}, "-")
fmt.Println(res)
//Case 3 sep is empty. It will output a string combined from the slice of strings
res = strings.Join([]string{"ab", "cd", "ef"}, "")
fmt.Println(res)
}

Output:

ab-cd-ef
abcdef

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2023 Welcome To Golang By Example | Design: Web XP