Golang. Character string into a numeric slice


Let’s write a simple program in Go that will take a string, break it down into slice elements, and convert each element into a number.

First, all the code, and I will break it down in detail below:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {

	r := bufio.NewReader(os.Stdin)

	str, _ := r.ReadString('\n')

	str = strings.TrimSpace(str)

	// str to slice
	s_str := strings.Split(str, " ")
	fmt.Println(s_str)

	s := make([]int, len(s_str))

	for i := range s_str {
		s[i], _ = strconv.Atoi(s_str[i])
		s[i] = s[i] + 1 // test
	}

	fmt.Println(s)

}

First we create a NewWriter r using the bufio package and standard input (os.Stdin).

Then we read the user input, a string of numbers separated by spaces, using the ReadString method, which returns the string before the argument \n, which indicates that the function should stop reading when it encounters a new string character.

The TrimSpace method is used to remove spaces from the beginning and end of the string, and the Split method is used to split the string into fragments based on the specified delimiter (in this case it’s the space) and store it to s_str.

Now we create a slice (slice) s of integers created with the make function with the length s_str and loop through it for, converting each string to an integer with the Atoi function from the strconv package.

Hallelujah, now we know how to convert a string of numbers separated by spaces into a slice of integers in Go 🙂


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.