Basic properties
- GO strings are UTF-8 encoding
- Fixed length, character occupies 1 byte is the ASCII code, another character occupies bytes 2-4
- C ++, Java and other languages are occupying a fixed length
- Benefit is not only to reduce the memory and hard disk space occupied, but also do not need that kind of text using UTF-8 character set encoding and decoding like other languages
- String immutable
string[0] = 'a'
Compile Error- You must first convert
[]byte
and then convert back, or use thestrings.Replace
function
- Gets the string in a byte addresses are illegal
- "" Wrapped string automatically escapes (eg \ n, \ r), `` wrapped string is output
- So json strings are wrapped with backticks
- String concatenation
- Overloaded when using the simplest manner operator +
- Use the plus sign + string concatenation is not the most efficient approach in the cycle, the better approach is to use the function strings.Join
- A better way is to use the byte buffer (for bytes.Buffer states) splice
var buffer bytes.Buffer
for {
if s, ok := getNextString(); ok {
buffer.WriteString(s)
} else {
break
}
}
fmt.Print(buffer.String(), "\n")
strings package
strings.HasPrefix(s, sub) bool
strings.HasSuffix(s, sub) bool
strings.Contains(s, sub) bool
strings.Index(s, sub) int // 返回-1表示找不到
strings.LastIndex(s, sub) int
strings.Replace(str, old, new, n) string // n为-1则替换所有old
strings.Count(s, sub) int
strings.Repeat(s, n) string // 重复n次字符串s,返回新字符串
strings.ToLower(s) string
strings.ToUpper(s) string
strings.TrimSpace(s) string// 剔除空白符
strings.Trim(s, cutset) string
strings.Feilds(s) []string //去除s字符串的空格符
strings.Split(s, sep) []string // 自定义分隔符sep
strings.Join(sl []string, sep string) string // 合并字符串
strconv package
strconv.Itoa(i int) string
strconv.Atoi(s string) (i int, err error)
// fmt表示格式('b'、'e'、'f'、'g');prec表示精度;bitSize用32表示float32,用64表示float64
strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string
strconv.ParseFloat(s string, bitSize int) (f float64, err error)
// 将bool等类型转换为字符串后,添加到现有的字节数组中
strconv.AppendBool(dst []byte, b bool) []byte
Regular match
//目标字符串
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
pat := "[0-9]+.[0-9]+" //正则
f := func(s string) string{
v, _ := strconv.ParseFloat(s, 32)
return strconv.FormatFloat(v * 2, 'f', 2, 32)
}
if ok, _ := regexp.Match(pat, []byte(searchIn)); ok {
fmt.Println("Match Found!")
}
re, _ := regexp.Compile(pat)
//将匹配到的部分替换为"##.#"
str := re.ReplaceAllString(searchIn, "##.#")
fmt.Println(str)
//参数为函数时
str2 := re.ReplaceAllStringFunc(searchIn, f)
fmt.Println(str2)
Export
Match Found!
John: ##.# William: ##.# Steve: ##.#
John: 5156.68 William: 9134.46 Steve: 11264.36