Golang語言包-字串處理strings和字串型別轉換strconv

frankphper發表於2019-05-07

Golang語言字串處理函式包strings,字串型別轉換包strconv。

/**
 * Golang語言字串處理函式包strings,字串型別轉換包strconv
 */
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    str := "This is an example of a string"
    fmt.Printf("Ture/False? Does the string \"%s\" have prefix %s?", str, "Th")
    // 判斷字串的字首
    fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
    fmt.Printf("True/False? Does the string \"%s\" have suffix %s?", str, "ing")
    // 判斷字串的字尾
    fmt.Printf("%t\n", strings.HasSuffix(str, "ing"))
    fmt.Printf("True/False? Does the string \"%s\" have %s?", str, "xa")
    // 判斷字串是否包含某字元
    fmt.Printf("%t\n", strings.Contains(str, "xa"))
    // 判斷指定字元在字串第一次出現的位置
    fmt.Printf("%d\n", strings.Index(str, "s"))
    // 判斷指定字元在字串最後一次出現的位置
    fmt.Printf("%d\n", strings.LastIndex(str, "s"))
    // 將字串中的前n個字元替換,並返回一個新字串,如果n=-1則替換所有字串中的字元
    fmt.Printf("%s\n", strings.Replace(str, "is", "at", 1))
    // 統計指定字元在字串中出現的次數
    fmt.Printf("%d\n", strings.Count(str, "s"))
    // 將字串重複n次,並返回新字串
    fmt.Printf("%s\n", strings.Repeat(str, 2))
    // 將字串全部轉換為小寫字元
    fmt.Printf("%s\n", strings.ToLower(str))
    // 將字串全部轉換為大寫字元
    fmt.Printf("%s\n", strings.ToUpper(str))
    // 去除字串開頭和結尾的空格
    str1 := " This is an example of a string "
    fmt.Printf("%s\n", strings.TrimSpace(str1))
    // 去除字串開頭和結尾的指定字元,只去除字串開頭或結尾的指定字元
    str2 := "my name is frank, this pencil is my"
    fmt.Printf("%s\n", strings.Trim(str2, "my"))
    fmt.Printf("%s\n", strings.TrimLeft(str2, "my"))
    fmt.Printf("%s\n", strings.TrimRight(str2, "my"))
    // 分割字串,轉換為一個slice
    // 利用1個或多個空白字元來作為分隔符,將字串分割成若干小塊,並返回一個slice
    // 如果字串只包含空白字串,則返回一個長度為0的slice
    sli := strings.Fields(str)
    for _, value := range sli {
        fmt.Println(value)
    }
    str3 := "2019-05-07"
    sli2 := strings.Split(str3, "-")
    for _, value := range sli2 {
        fmt.Println(value)
    }
    // 拼接slice元素成為一個字串
    fmt.Printf("%s\n", strings.Join(sli2, "-"))
    // 字串型別轉換
    str4 := "123"
    // 字串型別轉換為int
    num, _ := strconv.Atoi(str4)
    fmt.Printf("%d\n", num)
    // int轉換為字串型別
    newStr4 := strconv.Itoa(num)
    fmt.Printf("%s\n", newStr4)
}

執行結果:

Ture/False? Does the string "This is an example of a string" have prefix Th?true
True/False? Does the string "This is an example of a string" have suffix ing?true
True/False? Does the string "This is an example of a string" have xa?true
3
24
That is an example of a string
3
This is an example of a stringThis is an example of a string
this is an example of a string
THIS IS AN EXAMPLE OF A STRING
This is an example of a string
 name is frank, this pencil is 
 name is frank, this pencil is my
my name is frank, this pencil is 
This
is
an
example
of
a
string
2019
05
07
2019-05-07
123
123

相關文章