How to Convert String to Array in Golang

1. Introduction

In Go, a string is essentially a read-only slice of bytes. When we talk about converting a string to an array, we generally mean creating an array or a slice that represents the original string's individual characters or bytes.

This post will cover how to convert a string to both an array of bytes and an array of runes, as well as how to split a string into an array of substrings.

2. Program Steps

1. Convert a string to an array of bytes.

2. Convert a string to an array of runes.

3. Split a string by a delimiter into a slice of substrings.

3. Code Program

package main

import (
	"fmt"
	"strings"
)

func main() {
	// Example string
	myString := "hello"

	// Step 1: Convert a string to an array of bytes
	byteArray := []byte(myString)
	fmt.Println("Byte array:", byteArray)

	// Step 2: Convert a string to an array of runes
	runeArray := []rune(myString)
	fmt.Println("Rune array:", runeArray)

	// Example string to be split
	commaSeparated := "a,b,c,d,e"

	// Step 3: Split a string by a delimiter into a slice of substrings
	substrings := strings.Split(commaSeparated, ",")
	fmt.Println("Substrings:", substrings)
}

Output:

Byte array: [104 101 108 108 111]
Rune array: [104 101 108 108 111]
Substrings: [a b c d e]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "strings" - Importing packages for formatted output and string manipulation.

3. myString is defined as a simple string "hello".

4. The []byte(myString) conversion creates a slice of bytes (analogous to an array in other contexts) from myString.

5. The []rune(myString) conversion creates a slice of runes, which is necessary to properly handle Unicode characters since they can be more than one byte.

6. commaSeparated is a string that contains comma-separated values.

7. strings.Split function is used to split commaSeparated into a slice of substrings based on the comma delimiter.

8. fmt.Println prints the byte array, rune array, and slice of substrings to the console.

9. The output shows the conversion results for the byte and rune arrays and the substrings after splitting the comma-separated string.


Comments