How to Split a String in Golang - Golang String Tutorial

Published April 02, 2021


We know in programming language strings are sequence of characters. In Golang strings are different from other programming languages like java,python,rust programming language. Strings in golang is a read-only slice of bytes, these byte could be represented in the Unicode text by UTF-8 encoding. In this go programming language tutorial we are going to split a given string by using Split() function.

 

Split() function syntax

func Split(s, sep string) []string

 

In the above function 's' is the string which we need to split the string and 'sep'

 

Example to split a string with Split() golang

 

package main

import (
"fmt"
"strings"
)

// Main function
func main() {

  // Creating and initializing the strings
  str1 := "Golang, Split String, How to Split String"
  str2 := "Golang String examples"


  // Displaying strings
  fmt.Println("String 1: ", str1)
  fmt.Println("String 2: ", str2)


  // Splitting the given strings
  // Using Split() function
  res1 := strings.Split(str1, ",")
  res2 := strings.Split(str2, "")


  // Displaying the result

  fmt.Println("\nResult 1: ", res1)
  fmt.Println("Result 2: ", res2)


}

 

Execute at golang playgroung

Output:

String 1:  Golang, Split String, How to Split String
String 2:  Golang String examples

Result 1:  [Golang  Split String  How to Split String]
Result 2:  [G o l a n g   S t r i n g   e x a m p l e s]

 

Tags: go programming language tutorial, Split String,go language

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

217 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions