string of Golang (go Language) code tricks (String)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
    • Change some characters in a string
str := "hello roc"bytes  :=    ["  byte   ( str   bytes  [ 1  "    =     ' a '  str = string(bytes) //str == "hallo roc"
    • Intercept sub-strings
substr := str[n:m] //截取从索引n到m-1的子串
    • Traversing strings
//for遍历,此方式只能遍历存放ASCII//编码的字符串,比如中文就不行 forI:= 0;I<Len(Str);I++ {//... = str[i]}//for-range遍历,此方式可以遍历Unicode//编码的字符串,不担心乱码for   index  ,    char    :=   range str  { fmt.Printf("%d %c\n",index,char)}
    • Calculating string Lengths
//字符串中字符全为ASCII中的字符len(str)//字符串中含非ASCII的Unicode字符utf8.RuneCountInString(str)
    • Connection string
    The quickest notation:
var buf bytes.Bufferbuf.WriteString("hello ")buf   writestring   (  "Roc"  )  fmt.Println(buf.String()) //hello roc
There are two different ways:
str  :=   strings   join   ([]  string  {  "Hello"    "World"  },   ""   fmt.Println(str)
str := "hello"str += "roc"



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.