SoFunction
Updated on 2025-03-04

How to intercept strings by display length in go language

This article illustrates the method of snipping strings by display length in Go language. Share it for your reference. The specific analysis is as follows:

The string is intercepted according to the display length. The utf8 encoding used by PHP before, the difference in display lengths of 10 English and 10 Chinese characters is too big. If you intercept by bytes, you will have an error and intercept half a Chinese character, so you wrote these two functions.

I have been tossing golang these two days, so I rewritten a continuous function using golang. The code is as follows:

Copy the codeThe code is as follows:
package main
import (
    "fmt"
)
func main() {
(show_strlen("Haha1"))
(show_substr("Haha 1, what's 1", 9))
}

Extreme display length intercept string

Copy the codeThe code is as follows:
func show_substr(s string, l int) string {
    if len(s) <= l {
        return s
    }
    ss, sl, rl, rs := "", 0, 0, []rune(s)
    for _, r := range rs {
        rint := int(r)
        if rint < 128 {
            rl = 1
        } else {
            rl = 2
        }
        if sl + rl > l {
            break
        }
        sl += rl
        ss += string(r)
    }
    return ss
}

Get the display length according to the string display

Copy the codeThe code is as follows:
func show_strlen(s string) int {
    sl := 0
    rs := []rune(s)
    for _, r := range rs {
        rint := int(r)
        if rint < 128 {
            sl++
        } else {
            sl += 2
        }
    }
    return sl
}

I hope this article will be helpful to everyone's Go language programming.