3

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

ggorlen
  • 44,755
  • 7
  • 76
  • 106
gchristi001
  • 49
  • 1
  • 5

5 Answers5

6

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

ggorlen
  • 44,755
  • 7
  • 76
  • 106
zzn
  • 2,376
  • 16
  • 30
4

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

result := sentence[5:]

playground example

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
2

Since strings are UTF-8 encoded in Golang for single byte Unicode code points you may use result := sentence[5:]
like this working sample code:

package main

import "fmt"

func main() {
    sentence := "Kab. Kolaka Utara"
    result := sentence[5:]
    fmt.Println(result)
}

output:

Kolaka Utara

and for multibyte Unicode code points like "µµµµ Kolaka Utara" you may use string([]rune(sentence)[5:]), like this working sample code:

package main

import "fmt"

func main() {
    sentence := "µµµµ Kolaka Utara"
    result := string([]rune(sentence)[5:])
    fmt.Println(result)
}

output:

Kolaka Utara

and see Docs:

func Trim(s string, cutset string) string:

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

and see: Extracting substrings in Go

Graham
  • 7,431
  • 18
  • 59
  • 84
1

You should know the precise meaning of "trim" in programming: removing some characters both from the beginning and the end.

And in Golang's strings.Trim, The second argument is a set of characters.

Trim will remove all leading and trailing characters contained in the set.

In your example:

The set is

{"K", "a", ".", "b"};

For "Kab. Kolaka Utara", Trim will remove "Kab." from the beginning and "a" from the end.

So, the actual string you get is " Kolaka Utar" instead of "Kolaka Utar" which has no leading space.

If you just want to "trim" the first five characters, you should use this statement:

sentence = sentence[5:].
Calon
  • 4,174
  • 1
  • 19
  • 30
Tony Zhang
  • 49
  • 1
  • 4
0

If you are sure about how many characters to be trimmed. Use this method.

func main() {
    sentence := "Kab. Kolaka Utara"
    fmt.Println(sentence)
    fmt.Println(sentence[5:len(sentence)])

}

Output :

 Value :  Kab. Kolaka Utara
 Trimed : Kolaka Utara
pschilakanti
  • 903
  • 6
  • 7