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~