Problem with using strings.Split

Hello

I have problem with using strings.Split. The example from stackoverflow works perfecly fine - https://stackoverflow.com/questions/16551354/how-to-split-a-string-and-assign-it-to-variables-in-golang

My code on the other hand throws exception on access to s[1] element (acess to s[0] is ok) with “array out of bounds” error.

package main

import (
  "bufio"
  "fmt"
  "log"
  "os"
  "strings"
)
/*
// works great
func main() {
    s := strings.Split("127.0.0.1:5432", ":")
    ip, port := s[0], s[1]
    fmt.Println(ip, port)
}
*/
// doesnt work
func main() {
	lines, err := readLines("cookies.txt")
	if err != nil {
		log.Fatalf("readLines: %s", err)
	}
	for i, line := range lines {
		s := strings.Split(line, "	")
		fmt.Printf("\n%d :", i)
		fmt.Printf("%s", s[1])  
	}
}

// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	return lines, scanner.Err()
}

You should check the length of the returned slice before accessing it. More than that is hard to say without seeing the input data. Perhaps the file contains malformed entries or blank lines.

The length of array is 7 (as it should be) and the example input data is

www.socketloop.com	FALSE	/tutorials	FALSE	1500386325	__smVID	c311abdd45c8ffbecc545687fe5fce2b1c27dbcf9f3a33058e2bf5f05dba14d8
www.socketloop.com	FALSE	/tutorials	FALSE	1718546325	ezds	ffid%3D1%2Cw%3D1366%2Ch%3D768
www.socketloop.com	FALSE	/tutorials	FALSE	1718546325	ezohw	w%3D1366%2Ch%3D675
www.socketloop.com	FALSE	/tutorials	FALSE	1529330326	ezux_lpl_22847	1497794326095|7fc65836-22e5-4228-5d23-b812b03e5a5c
www.socketloop.com	FALSE	/tutorials	FALSE	0	ezux_et_22847	13
www.socketloop.com	FALSE	/tutorials	FALSE	0	ezux_tos_22847	22

If the length of s is seven, then you do not get an out of bounds panic for s[1]. I can’t reproduce your issue with that example data.

It’s probably a tab, not a space.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.