2

Let's say I have a string called varString.

varString := "Bob,Mark,"

QUESTION: How to remove the last letter from the string? In my case, it's the second comma.

Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

4 Answers4

7

How to remove the last letter from the string?


In Go, character strings are UTF-8 encoded. Unicode UTF-8 is a variable-length character encoding which uses one to four bytes per Unicode character (code point).

For example,

package main

import (
    "fmt"
    "unicode/utf8"
)

func trimLastChar(s string) string {
    r, size := utf8.DecodeLastRuneInString(s)
    if r == utf8.RuneError && (size == 0 || size == 1) {
        size = 0
    }
    return s[:len(s)-size]
}

func main() {
    s := "Bob,Mark,"
    fmt.Println(s)
    s = trimLastChar(s)
    fmt.Println(s)
}

Playground: https://play.golang.org/p/qyVYrjmBoVc

Output:

Bob,Mark,
Bob,Mark
peterSO
  • 158,998
  • 31
  • 281
  • 276
3

Here's a much simpler method that works for unicode strings too:

func removeLastRune(s string) string {
    r := []rune(s)
    return string(r[:len(r)-1])
}

Playground link: https://play.golang.org/p/ezsGUEz0F-D

hallazzang
  • 651
  • 8
  • 18
  • 2
    Alert: This is a very inefficient. If wastes CPU time and memory by unnecessarily converting the entire string to a slice of rines and the slice of runes to a string. – peterSO Jul 12 '19 at 14:43
  • 1
    @peterSO Admit, but that should matter if the input string is large enough. Most of the case this solution will do the job just fine. – hallazzang Jul 12 '19 at 14:45
  • 1
    Your answer is not "just fine". It is terrible. For the 9-character string in the question, it is 76.8 versus 4.51 ns/op, 17 times less efficient. For a 99-character string, it is 979 versus 4.50 ns/op, 217 times less efficient, and 528 B/op versus 0 B/op. Now, multiply that by Google scale. – peterSO Jul 12 '19 at 15:11
  • 10
    @peterSO I definitely agree with the fact that your solution is more efficient than mine, but here I showed 'simpler' solution, not faster. And I think it is not true only the speed of a program matters, especially when judging others' solution terrible or not. – hallazzang Jul 12 '19 at 22:42
0

Something like this:

s := "Bob,Mark,"
s = s[:len(s)-1]

Note that this does not work if the last character is not represented by just one byte.

Henry
  • 42,982
  • 7
  • 68
  • 84
0
newStr := strings.TrimRightFunc(str, func(r rune) bool {
    return !unicode.IsLetter(r) // or any other validation can go here
})

This will trim anything that isn't a letter on the right hand side.

Xibz
  • 356
  • 1
  • 5
  • 11