Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in golang to remove the last letter from the string?

Tags:

go

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.

like image 526
Nurzhan Nogerbek Avatar asked Oct 29 '25 16:10

Nurzhan Nogerbek


2 Answers

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
like image 123
peterSO Avatar answered Oct 31 '25 11:10

peterSO


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

like image 22
hallazzang Avatar answered Oct 31 '25 11:10

hallazzang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!