Original post

Hey all, hope you are having a nice day/evening. I was trying to learn how Split() method works on , and was wondering if there is any feature like rsplit() of Python in Go.

So what I have been trying is that getting a user input and split it by space, and store it into a slice called ‘hey’ and then print it. My code so far:

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {

        text := scanner.Text()
        if text == "0" {
            break
        }

        hey := strings.Split(text, " ")
        fmt.Println(hey)
    }
}

And I am expecting user input to be in the form of

city-name longitude langitude

in one line. So for example, if a user types

London 185 86

then hey slice will be {London 185 86} and it is working as I expected.

But the problem is that when user types a city name with space in it, such as “Buenos Aires”. So that the user input will be like “Buenos Aires 185 86”.

I want hey slice to be {Buenos Aires 185 86} in that case, is there any good way to do this in Go? This can be done with rsplit(” “, 2) in Python but I have googled to find such a way and read the documentation but could not find it. Can anyone help me with this?

I’d probably do something like this

   fields := strings.Fields("Buenos Aires 185 86")
        for len(fields) > 3 {
                fields[1] = fields[0] + " " + fields[1]
                fields = fields[1:]
        }

Playground

Because the cities could have multiple words in the name perhaps a better idea is to read the words and check the type of each one (string or numeric) and concatenate only the strings…