How to slice a rune in Go

16 March 2015   0 comments   Go

Powered by Fusion×

Strangely this was hard. The solution looks easy but it took me a lot of time to get this right.

What I want to do is split a string up into a slice of parts. For example:

word := "peter"
for i := 1; i <= len(word); i++ {
    fmt.Println(word[0:i])
}

The output is:

p
pe
pet
pete
peter

Play here.

Now, what if the word you want to split contains non-ascii characters? As a string "é" is two characters internally. So you can't split them up. See this play and press "Run".

So, the solution is to iterate over the string and Go will give you an index of each unicode character. But you'll want to skip the first one.

word := "péter"
for i, _ := range word {
    if i > 0 {
        fmt.Println(word[0:i])
    }
}
fmt.Println(word)

You can play with it here in this play.

Now the output is the same as what we got in the first example but with unicode characters in it.

p
pé
pét
péte
péter

I bet this is obvious to the gurus who've properly read the documentation but it certainly took me some time to figure it out and so I thought I'd share it.

Comments

Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
Air Mozilla on Roku 05 March 2015
Next:
Bye bye httpretty. Welcome back good old mock! 19 March 2015
Related by Keyword:
Unzip benchmark on AWS EC2 c3.large vs c4.large 29 November 2017
Autocompeter is Dead. Long live Autocompeter! 09 January 2017
Go vs. Python 24 October 2014
String comparison function in Python (alpha) 22 December 2007
is is not the same as equal in Python 01 December 2006
Related by Text:
Best non-cryptographic hashing function in Python (size and speed) 21 February 2015
String comparison function in Python (alpha) 22 December 2007
Jacobian highlighter 02 May 2005
Too much Python makes Peter a shit Javascript developer 13 March 2009
CSS selector simplifier regular expression in JavaScript 20 December 2017