Go string Capture Notes

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

When I first encountered the need to intercept the string in the Go language programming process, the first thought is that the strings package may have the relevant method ~

I'm still too young to be spoiled by scripting language all these years.

Well, you can only do it yourself, the idea is very clear, turn the string into a byte array, and then use the slice slice to get one of the sections that you want to intercept, and then revert to a string by forcing the type conversion by T (), which is simple at first:

s := "abcdefg"s = string([]byte(s)[:3])fmt.Println(s) //得到 "abc"

It seems simple, but what if I encounter Chinese? According to Common sense, a Chinese character must be more than one byte, I have to traverse each byte, determine the encoding, determine the ASCII code range? That's too much trouble, of course, if you have to deal with it, it is certain that people have built the wheel, Google will have a harvest.

Fortunately, I don't have to think about that much, except that byte has another type of rune, using it completely regardless of the Unicode byte problem, a Chinese just stand an array subscript, the code is very simple:

s := "a我cd"s = string([]rune(s)[:3])fmt.Println(s) //得到 "a我c"

So, because slice, string interception is very flexible.

However, think of PHP built so many convenient functions, sure enough PHP is the world's best language O (∩_∩) o~

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.