golang strings 字符串操作

判断

  • EqualFold

判断两个字符串是否相等, 不区分大小写


 bool := strings.EqualFold("Home", "home")
    
// -> true

  • HasPrefix

是否包含某前缀, 区分大小写


 bool := strings.HasPrefix("Home", "h")
 
// -> false

  • HasSuffix

是否包含某一后缀, 区分大小写


 bool := strings.HasSuffix("Home", "me")
 
 // -> true

  • Contains

是否包含某字串, 区分大小写


bool := strings.Contains("HOME", "ho")

// -> false

位置

  • Index

字符首次出现的位置,不存在返回 -1


position := strings.Index("lorem lorem", "lo")

// -> 0

  • IndexFunc

返回满足回调函数字符首次出现的位置


num := strings.IndexFunc("me", func(r rune)bool {
    return r == rune('m')
})

// -> 0

  • LastIndex

返回字符串,最后一次出现的位置


num := strings.LastIndex("mm", "m")

// -> 1

  • LastIndexFunc

返回满足回调函数 的字符最后出现的位置, 使用方法与 IndexFunc 相同

转换

  • Title

返回单词首字母大写的拷贝


str := strings.Title("go home")
// -> Go Home

  • ToLower

返回字符全小写拷贝


str := strings.ToLower("GO HOME")

// -> go home

  • ToUpper

返回字符全大写拷贝


str := string.ToUpper("go home")
// -> GO HOME

重复/替换

  • Repeat

字符串重复n次


str := strings.Repeat("m", 3)
// -> mmm

  • Replace

字符串替换

/*
    参数
    [string] 被处理字符
    [string] 匹配字符
    [string] 替换字符
    [int] 替换个数
*/
str := strings.Replace("co co co co", "co", "jc", 2)

  • Trim

去除前后缀


str := strings.Trim(" - title - ", "-")

// title

  • TrimSpace

去除前后空格

切分

  • Fields

按照空格 分割字符


strs := strings.Fields("coco jeck")
// -> [coco jeck]
  • FieldsFunc

根据回调 分割字符, 回调函数接收 rune 作为参数


// 使用逗号分割
str := strings.FieldsFunc("coco,jeck,andy", func(r rune) bool {
    return r == rune(',')
})

// -> [coco jeck andy]

  • Split

使用指定字符作为分割符


str := strings.Split("product/id/place", "/")

// -> [product id place]
  • SplitN

指定切分数量的Split


str := strings.Split("product/id/place", "/", 2)

// -> [product id/place]

  • Join

合并字符串


str := strings.Join([]string{"coco", "jeck"}, ",")

// -> coco,jeck

读写

获取字符串的io对象

  • NewRead

创建字符串 Reader

  • NewRepacer

创建字符串替换对象

你可能感兴趣的:(golang strings 字符串操作)