Go language method of intercepting strings by display length _golang

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.