哪种方法可以在Go中修剪字符串变量的前导和尾随空格?
答案 0 :(得分:219)
例如,
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"
答案 1 :(得分:30)
在go中有很多函数可以修剪字符串。
在那里看到他们:Trim
这是一个根据文档改编的示例,删除了前导和尾随空格:
fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
答案 2 :(得分:7)
为了修剪你的字符串,Go'字符串"包具有TrimSpace()
,Trim()
函数,用于修剪前导和尾随空格。
查看documentation以获取更多信息。
答案 3 :(得分:7)
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
输出: 你好,地鼠
答案 4 :(得分:0)
正如@Kabeer所提到的,你可以使用TrimSpace,这是golang文档中的一个例子:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
答案 5 :(得分:0)
@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))
}
您也可以在Go lang playground中找到它。
答案 6 :(得分:0)
带有JSON Unmarshall的快速字符串“ GOTCHA” ,它将在字符串中添加环绕引号。
(示例:字符串值{"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
}
答案 7 :(得分:0)
我对性能很感兴趣,所以我做了一个只修剪左边的比较 侧面:
timestamp_seconds = beginning_df.select(from_unixtime("float_seconds"))
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