Old Shong Golang notes-string

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

A large number of string operations are involved in all programming languages, and it can be seen how important it is to be familiar with how strings are manipulated. The string in go is the same as in C #, and the string content cannot be modified after initialization. It is important to note that in go the string is UTF-8 encoded, note that the file encoding format is changed to UTF-8 (especially under Windows) when saving the file.

Initialization

var str string //声明一个字符串str = "laoYu"  //赋值ch :=str[0]    //获取第一个字符len :=len(str) //字符串的长度,len是内置函数 ,len=5

String manipulation

The encoding process can not avoid the Chinese characters, then how can we extract an English? First we need to know that String[index] gets the character byte and cannot be taken as a C # "老虞"[0] Old ', you need to convert a string into a rune array in go, and the Runne array can get the Unicode code identified by an array subscript, then the Unicode code is created as a string.

View Sample Code

str :="laoYu老虞"for  i:=0;i<len(str);i++ {         fmt.Println(str[i])}for  i,s :=  range str {        fmt.Println(i,"Unicode(",s,") string=",string(s))}r := []rune(str)fmt.Println("rune=",r)for i:=0;i<len(r) ; i++ {       fmt.Println("r[",i,"]=",r[i],"string=",string(r[i]))}Outut:10897111891172321281292321531580 Unicode( 108 ) string= l1 Unicode( 97 ) string= a2 Unicode( 111 ) string= o3 Unicode( 89 ) string= Y4 Unicode( 117 ) string= u5 Unicode( 32769 ) string= 老8 Unicode( 34398 ) string= 虞rune= [108 97 111 89 117 32769 34398]r[ 0 ]= 108 string= lr[ 1 ]= 97 string= ar[ 2 ]= 111 string= or[ 3 ]= 89 string= Yr[ 4 ]= 117 string= ur[ 5 ]= 32769 string= 老r[ 6 ]= 34398 string= 虞

It is important to manipulate strings to understand which functions are available in the next strings package

gets the total number of bytesfunc Len(v type) int

The Len function is a built-in function in go that can be used without introducing a strings package. Len (String) returns the number of bytes in a string. The parameter types supported by the Len function are as follows:

  • The number of elements in the Len (array) array
  • The number of elements in the Len (*array) array pointer, or 0 if the entry parameter is nil
  • The number of elements in the Len (Slice) array slice, and returns 0 if the entry parameter is nil
  • The number of elements in the Len (map) dictionary, or 0 if the entry parameter is nil
  • Len (channel) channel buffer number of elements in queue

View Sample Code

str: = "Laoyu old specter" str2: = "Laoyu" FMT. Println ("Len (", "str,") = ", Len (str))//len=11=5+6, a Chinese character that accounts for 3 bytes of FMT in utf-8>. Println ("Len (", "str2,") = ", Len (str2))//len=5fmt. Println ("str[0]=", Str[0])//lstr: = "str" arr: =[5]int{1,2,3}slice: =make ([]int,5) m: =make (Map[int] string) m[2] = "Len" ch: =make (chan int) fmt. Println ("len (String) =", Len (str))//3fmt. Println ("len (array) =", Len (arr))//5invalid argument user (type *userinfo) for lenfmt. Println ("len (slice) =", Len (slice))//5fmt. Println ("len (map) =", Len (m))//1fmt. Println ("len (chat) =", Len (CH))//0//user: =&userinfo{id:1,name: "Laoyu"}//interger: =2//fmt. Println ("Len (my struct) =", Len (user))//invalid argument user (type *userinfo) for len//fmt. Println ("len (Interger) =", Len (Interger)) var str2 stringvar arr2 [5]intvar slice2 []intvar m2 map[int] stringvar ch2 cha N intfmt. Println ("len (String) =", Len (str2))//0fmt. Println ("len (array) =", Len (arr2))//5 FMT. Println ("len (slice) =", Len (Slice2))//0fmt. Println ("len (map) =", Len (m2))//0fmt. Println ("len (chat) =", Len (CH2))//0

whether the string contains a stringfunc Contains(s, substr string) bool

Determines whether a string is included, which is case-sensitive. The interior is actually implemented through the index (s,sub string) int. If the index!=-1 represents the string that is contained. The empty string "" exists in any string.

Source

// Contains returns true if substr is within s.func Contains(s, substr string) bool {     return Index(s, substr) != -1}

* * example, use Import Package: ' Import ' strings ' * *

View Sample Code

str :="laoYuStudyGotrue是否包含某字符串"fmt.Println(strings.Contains(str,"go"))         //falsefmt.Println(strings.Contains(str,"Go"))         //truefmt.Println(strings.Contains(str,"laoyu"))      //falsefmt.Println(strings.Contains(str,"是"))         //true    fmt.Println(strings.Contains(str,""))               //true

In practice, it is often necessary to confirm the inclusion of a string in case-insensitive cases (we should reduce this so that a case conversion is required for each validation). Here I partially modify the source code to provide a validation string containing a string of functions, of course, you can also directly use strings. Contains (Strings. ToLower (s), strings. ToLower (SUBSTR))

str := "laoYuStudyGotrue是否包含某字符串"fmt.Println(Contains(str, "go", true))  //truefmt.Println(Contains(str,"go",false))   //false
    Whether the string s contains a string substr,ignorecase indicates whether the case is ignored, func Contains (s string, substr string, ignoreCase bool) bool { Return index (S, substr, ignoreCase)! =-1}//String subst the index position in the string s, ignoreCase indicates whether to ignore casing func index (s string, Sep s            Tring, ignoreCase bool) int {n: = Len (Sep) If n = = 0 {return 0} To Lower if ignoreCase = = true {s = strings. ToLower (s) Sep = strings. ToLower (Sep)} c: = Sep[0] if n = = 1 {//special case worth making FA St for I: = 0; I < Len (s);                    i++ {if s[i] = = c {return i} } return-1}//n > 1 for i: = 0; I+n <= Len (s);                    i++ {if s[i] = = c && s[i:i+n] = = Sep {        Return i}} return-1} 

gets the number of occurrences of the string Sep in the string sCount(s,sep string)

Note: If sep= "", then no matter why the string will return Len (s) +1

View Sample Code

fmt.Println(strings.Count("laoYuStudyGo", "o"))                 //2fmt.Println(strings.Count("laoYuStudyGo", "O"))                 //0fmt.Println(strings.Count("laoYuStudyGo", ""))                  //13=12+1fmt.Println(strings.Count("laoYuStudyGo老虞学习Go语言", "虞"))  //1fmt.Println(strings.Count("laoYuStudyGo老虞学习Go语言", "Go"))  //2fmt.Println(strings.Count("laoYuStudyGo老虞学习Go语言", "老虞"))//1fmt.Println(strings.Count("", ""))                             //1=0+1fmt.Println(strings.Count("aaaaaaaa","aa"))                     //4fmt.Println(strings.Count("laoYuStudyGo_n","\n"))               //0

* * Use (multiple) spaces to split the string fields (s string), returning the segmented array * *

Splits a string into an array, with a delimiter of spaces.

View Sample Code

fmt.Println(strings.Fields("lao Yu Study Go ")) //OutPut: [lao Yu Study Go]fmt.Println(strings.Fields("   Go    "))        //[Go]fmt.Println(strings.Fields(""))                 //[]fmt.Println(strings.Fields(" \n go"))           //[go]

* * In fact, its internal implementation is called Fieldsfunc (S,unicode. IsSpace), we can also customize the partitioning method * *

canSplit := func (c rune)  bool { return c=='#'}fmt.Println(strings.FieldsFunc("lao###Yu#Study####Go#G ",canSplit)) //[lao Yu Study Go G<space>]

checks whether a string begins with a string Hasprefix (S,prefix string) bool

If you want to see more about the string manipulation functions under the strings package, see

    • Official Strings Package Address
    • The corresponding function translation address
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.