go實踐二十六 字符串處理

編輯一個 teststring.go 文件,內容如下

使用 go run teststring.go 運行該文件即可

package main

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


func main() {
	fmt.Println("teststring")
	teststring()

	fmt.Println()
	fmt.Println("stringexchange")
	stringexchange()
}

func teststring(){
	var result interface{}
	/*
	func Contains(s, substr string) bool
	字符串s中是否包含substr,返回bool值
	*/
	result = strings.Contains("hello world","hello")
	fmt.Println("判斷字符串是否存在",result)
	result = strings.Contains("hello world","hellow")
	fmt.Println("判斷字符串是否存在",result)

	/*
	func Join(a []string, sep string) string
	字符串鏈接,把slice a通過sep鏈接起來
	*/
	arr := []string{
		"hello",
		"world",
	}
	result = strings.Join(arr,",")
	fmt.Println("字符串鏈接",result)

	/*
	func Index(s, sep string) int
	在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
	*/
	result = strings.Index("hello world","world")
	fmt.Println("字符串位置",result)
	result = strings.Index("hello world","world2")
	fmt.Println("字符串位置",result)

	/*
	func Repeat(s string, count int) string
	重複s字符串count次,最後返回重複的字符串
	*/
	result = strings.Repeat("hello ",2)
	fmt.Println("重複的字符串",result)

	/*
	func Replace(s, old, new string, n int) string
	在s字符串中,把old字符串替換爲new字符串,n表示替換的次數,小於0表示全部替換
	*/
	result = strings.Replace("hello world","hello ","hello",-1)
	fmt.Println("字符串替換",result)

	/*
	func Split(s, sep string) []string
	把s字符串按照sep分割,返回slice
	*/
	result = strings.Split("hello world"," ")
	fmt.Println("字符串切割",result)

	/*
	func Trim(s string, cutset string) string
	在s字符串的頭部和尾部去除cutset指定的字符串
	*/
	result = strings.Trim("hello world !!!"," !!!")
	fmt.Println("字符串Trim",result)

	/*
	func Fields(s string) []string
	去除s字符串的空格符,並且按照空格分割返回slice
	*/
	result = strings.Fields("a b  c   d    e")
	fmt.Println("字符串Fields切割",result)
}

func stringexchange(){
	/*
	字符串轉換
	字符串轉化的函數在strconv中,如下也只是列出一些常用的:
	*/
	/*
	Append 系列函數將整數等轉換爲字符串後,添加到現有的字節數組中。
	*/
	result := make([]byte,0,100)
	result = strconv.AppendInt(result,4567,10)
	result = strconv.AppendBool(result,false)
	result = strconv.AppendQuote(result,"abcdefg")
	result = strconv.AppendQuoteRune(result,'單')
	fmt.Println("字符串Append",string(result))

	/*
	Format 系列函數把其他類型的轉換爲字符串
	*/
	a := strconv.FormatBool(false)
	b := strconv.FormatFloat(123.33,'g',12,64)
	c := strconv.FormatInt(1234,10)
	d := strconv.FormatUint(12345,10)
	e := strconv.Itoa(1023)
	fmt.Println("字符串Format",a,b,c,d,e)

	/*
	Parse 系列函數把字符串轉換爲其他類型
	*/
	p1,err := strconv.ParseBool("false")
	checkError(err)
	p2,err := strconv.ParseFloat("123.23",64)
	checkError(err)
	p3,err := strconv.ParseInt("1234",10,64)
	checkError(err)
	p4,err := strconv.ParseUint("12345",10,64)
	checkError(err)
	p5,err := strconv.Atoi("1023")
	checkError(err)
	fmt.Println("字符串Parse",p1,p2,p3,p4,p5)
}

func checkError(e error){
	if e != nil{
		fmt.Println(e)
	}
}

參考:https://www.golang123.com/books/9/chapters/183

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章