Skip to content

Instantly share code, notes, and snippets.

@sisteamnik
Created December 1, 2014 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sisteamnik/c866cb7eed264ea3408d to your computer and use it in GitHub Desktop.
Save sisteamnik/c866cb7eed264ea3408d to your computer and use it in GitHub Desktop.
Golang substring for multi byte 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], "")
}
@sisteamnik
Copy link
Author

Play it play.golang.com

@shamimevatix
Copy link

Thanks

@xeoncross
Copy link

Why not use foo := []rune(stringhere) instead?

@gonejack
Copy link

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