Is there anything like Python's rsplit() in Go?

Hey all, hope you are having a nice day/evening. I was trying to learn how Split() method works on Go, 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

1 Like

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…

1 Like

This sounds like a good idea, but how can I do this?

A quick and trivial solution that came into my mind look like this:

package main

import (
    "fmt"
    "strconv"
    "strings"
)

const data = "Buenos Aires 185 86"

func main() {

    var city string
    var long, lat int

    for i, fields := 0, strings.Fields(data); i < len(fields); i++ {
    	if _, err := strconv.Atoi(fields[i]); err != nil {
    		city = city + fields[i] + " "
    		continue
    	}
    	long, _ = strconv.Atoi(fields[i])
    	lat, _ = strconv.Atoi(fields[i+1])
    	city = city[:len(city)-1]
    	break
    }
	fmt.Printf("%s, [%d %d]\n", city, long, lat)
}

You can also try with a more complex name like Edinburgh of the Seven Seas.

1 Like

Thank you so much for kind reply!

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