字符串输入可能包含太多的空格,太少的空格或不适合的空格字符。此篇包含有关如何管理这些内容并根据需要格式化字符串的提示。
管理字符串中的空格
Golang 版本
1.12.1
前言
字符串输入可能包含太多的空格,太少的空格或不适合的空格字符。此篇包含有关如何管理这些内容并根据需要格式化字符串的提示。
实现
创建文件whitespace.go
,代码如下:
package main
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
func main() {
stringToTrim := "\t\t\n Go \tis\t Awesome \t\t"
trimResult := strings.TrimSpace(stringToTrim)
fmt.Println(trimResult)
stringWithSpaces := "\t\t\n Go \tis\n Awesome \t\t"
r := regexp.MustCompile("\\s+")
replace := r.ReplaceAllString(stringWithSpaces, " ")
fmt.Println(replace)
needSpace := "need space"
fmt.Println(pad(needSpace, 14, "CENTER"))
fmt.Println(pad(needSpace, 14, "LEFT"))
}
func pad(input string, padLen int, align string) string {
inputLen := len(input)
if inputLen >= padLen {
return input
}
repeat := padLen - inputLen
var output string
switch align {
case "RIGHT":
output = fmt.Sprintf("% "+strconv.Itoa(-padLen)+"s", input)
case "LEFT":
output = fmt.Sprintf("% "+strconv.Itoa(padLen)+"s", input)
case "CENTER":
bothRepeat := float64(repeat) / float64(2)
left := int(math.Floor(bothRepeat)) + inputLen
right := int(math.Ceil(bothRepeat))
output = fmt.Sprintf("% "+strconv.Itoa(left)+"s%"+strconv.Itoa(right)+"s", input, "")
}
return output
}
$ go run whitespace.go
Go is Awesome
Go is Awesome
need space
need space
原理
在代码处理字符串之前对其进行修剪是非常常见的实践,正如前面的代码所演示的,这很容易由标准的Go库完成。strings
库还提供了TrimXXX
函数的更多变体,它还允许从字符串中修剪其他字符。
要修剪前边和结尾的空白,可以使用strings
包的TrimSpace
函数。这代表了代码的以下部分,这也包括在前面的例子中:
stringToTrim := "\t\t\n Go \tis\t Awesome \t\t"
stringToTrim = strings.TrimSpace(stringToTrim)
regex
包适合替换多个空格和制表符,并且可以用这种方式为进一步处理字符串做好准备。注意,使用此方法,中断行被替换为单个空格。
这部分代码表示使用正则表达式将所有多个空格替换为一个空格:
r := regexp.MustCompile("\\s+")
replace := r.ReplaceAllString(stringToTrim, " ")
填充不是string
包的显式函数,但是可以通过fmt
包的Sprintf
函数来实现。代码中的pad
函数使用格式化模式% <+/-padding>s
和一些简单的数学运算来查找填充。最后,填充数字前的负号作为右pad,而正数作为左pad。