Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Strings Trim Function

Tags:

string

trim

go

I used strings.Trim() in Golang to trim the first five characters.
However, the last "a" is always gone.
Why is that so?

Example:

sentence := "Kab. Kolaka Utara"
result := strings.Trim(sentence,sentence[:4])
fmt.Println(result)

Result: Kolaka Utar

I expected: Kolaka Utara

https://play.golang.org/p/R6UoKWNaVv

like image 238
gchristi001 Avatar asked Aug 30 '26 04:08

gchristi001


2 Answers

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

sentence[:4] is "Kab." Trim will remove all leading and trailing "k", "a", "b", ".".

https://golang.org/pkg/strings/#Trim

like image 107
zzn Avatar answered Sep 01 '26 05:09

zzn


If you want to trim the first 5 bytes, then use:

result := sentence[5:]

playground example