在Go中,哪一种有效的方法来修剪字符串变量的前导和尾随空白?
在go中有很多修剪字符串的函数。
看到了吧:修剪
下面是一个例子,改编自文档,删除了前导和后面的空白:
fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
strings.TrimSpace (s)
例如,
package main
import (
"fmt"
"strings"
)
func main() {
s := "\t Hello, World\n "
fmt.Printf("%d %q\n", len(s), s)
t := strings.TrimSpace(s)
fmt.Printf("%d %q\n", len(t), t)
}
输出:
16 "\t Hello, World\n "
12 "Hello, World"
就像@Kabeer提到的,你可以使用TrimSpace,这里有一个来自golang文档的例子:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
输出: 你好,打地鼠
点击这个链接——https://golang.org/pkg/strings/#TrimSpace
@peterSO有正确答案。我在这里添加了更多的例子:
package main
import (
"fmt"
strings "strings"
)
func main() {
test := "\t pdftk 2.0.2 \n"
result := strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r pdftk 2.0.2 \n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\r pdftk 2.0.2 \r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
}
你也可以在围棋场上找到它。
一个快速字符串“GOTCHA”与JSON Unmarshall将添加包装引号字符串。
(例如:字符串值{"first_name":" I have whitespace "}将转换为"\" I have whitespace \"")
在你可以修剪任何东西之前,你需要先删除额外的引号:
操场上的例子
// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string
// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
ns := string(data)
// Make sure we don't have a blank string of "\"\"".
if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
*s = ""
return nil
}
// Remove the added wrapping quotes.
ns, err := strconv.Unquote(ns)
if err != nil {
return err
}
// We can now trim the whitespace.
*s = ScrubString(strings.TrimSpace(ns))
return nil
}
我对性能很感兴趣,所以我做了一个比较,只修剪左边 的一面:
package main
import (
"strings"
"testing"
)
var s = strings.Repeat("A", 63) + "B"
func BenchmarkTrimLeftFunc(b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.TrimLeftFunc(s, func(r rune) bool {
return r == 'A'
})
}
}
func BenchmarkIndexFunc(b *testing.B) {
for n := 0; n < b.N; n++ {
i := strings.IndexFunc(s, func(r rune) bool {
return r != 'A'
})
_ = s[i]
}
}
func BenchmarkTrimLeft(b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.TrimLeft(s, "A")
}
}
TrimLeftFunc和IndexFunc是一样的,TrimLeft要慢一些:
BenchmarkTrimLeftFunc-12 10325200 116.0 ns/op
BenchmarkIndexFunc-12 10344336 116.6 ns/op
BenchmarkTrimLeft-12 6485059 183.6 ns/op