This example describes how the go language intercepts strings by display length. Share to everyone for your reference. The specific analysis is as follows:
Intercept the string according to the display length, before PHP uses the UTF8 code, 10 English and 10 Chinese characters display length gap is too big, by byte intercept of words and will be intercepted half Chinese characters, so write these two functions.
These two days in toss Golang, so use Golang rewrite a function. The code is as follows:
Copy Code code as follows:
Package Main
Import (
"FMT"
)
Func Main () {
Fmt. Println (Show_strlen ("haha 1"))
Fmt. Println (Show_substr ("haha 1 what 1 mody", 9))
}
Eradicate display length intercept string
Copy Code code 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 display length based on string display
Copy Code code 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 help you with your go language program.