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?
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…
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.