Created
December 1, 2014 08:52
-
-
Save sisteamnik/c866cb7eed264ea3408d to your computer and use it in GitHub Desktop.
Golang substring for multi byte characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//simple substring algorithm for multi byte characters written in golang | |
//try it http://play.golang.org/p/whbzj3VgSG | |
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
func main() { | |
fmt.Println(substr("хлеб", 2, 2)) | |
fmt.Println(substr("僤凘墈 葎萻萶 銈 磑禠", 2, 6)) | |
} | |
func substr(s string, from, length int) string { | |
//create array like string view | |
wb := []string{} | |
wb = strings.Split(s, "") | |
//miss nil pointer error | |
to := from + length | |
if to > len(wb) { | |
to = len(wb) | |
} | |
if from > len(wb) { | |
from = len(wb) | |
} | |
return strings.Join(wb[from:to], "") | |
} |
For recent Go:
string([]rune(origin)[start:end])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not use
foo := []rune(stringhere)
instead?