Golang to intercept strings by display length

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

According to the length of the display to intercept the string, before PHP with the UTF8 encoding, 10 English and 10 Chinese characters of the display length gap is too large, by byte interception will be wrong to intercept half of Chinese characters, so write these two functions.

The two days in the toss Golang, so you use Golang rewrite a function. The code is as follows:

Package main       Import (    "FMT")       func Main () {    fmt. Println (Show_strlen ("haha 1"))    FMT. Println (Show_substr ("haha 1 1", 9)}

Eradicate display length intercept string

Func Show_substr (s string, L int) string {    If Len (s) <= L {        return s    }    SS, SL, RL, rs: = "", 0, 0, []ru NE (s)    for _, R: = Range rs {        rint: = Int (r)        if rint < {            RL = 1        } else {            RL = 2        }               If SL + RL > L {            break        }        SL + RL        SS + = string (r)    }    return SS}

Get display length based on string display

 func Show_strlen (s string) int {sl: = 0 rs: = []rune (s) for _, R: = Range rs {rint: = Int (r) If rint < {sl++} else {SL + 2}} return SL} 
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.