Golang program to convert the arraylist into string and vice-versa


In go we can use strings.Join to convert a arraylist into string. Here we will understand how we can use strings.Join to combine multiple texts from an array that are separated by commas and spaces also, strings. To create an array of strings, use the Split function on the string. Let’s see through the code and algorithm how its executed.

Syntax

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

The join function is used to convert an array to string. This function is present in strings package. it takes two arguments first one is the array that we wish to convert and second is the separation with which the array elements should be separated once they are converted to strings and returns the final string.

func Split(str, sep string) []string

Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) and strings package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a main function and in that function first convert array into string by creating an array and assigning it some values of type string.

  • Step 3 − In the next step use strings.Join function to join the elements of the array with , as the separator between them.

  • Step 4 − Print the string converted from array on the console using fmt.Println() function where ln refers to new line.

  • Step 5 − In the next case convert string into array by creating string and giving it similar elements as in the first case.

  • Step 6 − Here, use strings.Split function with , as the separator between the elements.

  • Step 7 − Print the string converted array on the console similarly as printed in step4.

Example

In this example we will convert arraylist into string.

package main
import (
   "fmt"
   "strings"
)

func main() {
   // Array to String
   arr := []string{"India", "Canada", "Italy"}
   str := strings.Join(arr, ", ")
   fmt.Println("Array to String:", str)

   // String to Array
   str = "India, Canada, Italy"
   arr = strings.Split(str, ", ")
   fmt.Println("String to Array:", arr)
}

Output

Array to String: India, Canada, Italy
String to Array: [India Canada Italy]

Conclusion

We execute the program of converting arraylist into string and vice-versa using an example. In that particular example we have used two built-in functions named strings.Split and strings.Join to execute the program.

Updated on: 21-Feb-2023

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements