如何去除字符串的前导和尾随空格?

huangapple go评论73阅读模式
英文:

How to trim leading and trailing white spaces of a string?

问题

在Go语言中,修剪字符串变量的前导和尾随空格的有效方法是使用strings包中的TrimSpace函数。TrimSpace函数会返回一个新的字符串,其中移除了原始字符串前导和尾随的空格。你可以按照以下方式使用TrimSpace函数:

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "   Hello, World!   "
	trimmedStr := strings.TrimSpace(str)
	fmt.Println(trimmedStr) // 输出: "Hello, World!"
}

在上面的示例中,我们使用TrimSpace函数修剪了字符串变量str的前导和尾随空格,并将结果存储在trimmedStr变量中。最后,我们打印出修剪后的字符串。

英文:

Which is the effective way to trim the leading and trailing white spaces of string variable in Go?

答案1

得分: 338

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"
英文:

strings.TrimSpace(s)

For example,

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)
}

Output:

16 "\t Hello, World\n "
12 "Hello, World"

答案2

得分: 41

在Go语言中有一系列用于修剪字符串的函数。

在这里可以看到它们:Trim

这是一个示例,改编自文档,用于删除前导和尾随的空格:

fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
英文:

There's a bunch of functions to trim strings in go.

See them there : Trim

Here's an example, adapted from the documentation, removing leading and trailing white spaces :

fmt.Printf("[%q]", strings.Trim(" Achtung  ", " "))

答案3

得分: 9

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

输出:
Hello, Gophers

你可以通过这个链接查看更多信息:https://golang.org/pkg/strings/#TrimSpace

英文:
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

> Output:
> Hello, Gophers

And simply follow this link - https://golang.org/pkg/strings/#TrimSpace

答案4

得分: 8

为了修剪你的字符串,Go语言的"strings"包提供了TrimSpace()Trim()函数,可以修剪字符串前后的空格。

更多信息请查阅文档

英文:

For trimming your string, Go's "strings" package have TrimSpace(), Trim() function that trims leading and trailing spaces.

Check the documentation for more information.

答案5

得分: 0

@peterSO的答案是正确的。我在这里添加更多的示例:

package main

import (
	"fmt"
	strings "strings"
)

func main() { 
	test := "\t pdftk 2.0.2  \n"
	result := strings.TrimSpace(test)
	fmt.Printf("字符串 %q 的长度为 %d\n", test, len(test))
	fmt.Printf("字符串 %q 的长度为 %d\n\n", result, len(result))
	
	test = "\n\r pdftk 2.0.2 \n\r"
	result = strings.TrimSpace(test)
	fmt.Printf("字符串 %q 的长度为 %d\n", test, len(test))
	fmt.Printf("字符串 %q 的长度为 %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("字符串 %q 的长度为 %d\n", test, len(test))
	fmt.Printf("字符串 %q 的长度为 %d\n\n", result, len(result))
	
	test = "\r pdftk 2.0.2 \r"
	result = strings.TrimSpace(test)
	fmt.Printf("字符串 %q 的长度为 %d\n", test, len(test))
	fmt.Printf("字符串 %q 的长度为 %d\n\n", result, len(result))	
}

你也可以在Go语言 playground中找到这个示例。

英文:

@peterSO has correct answer. I am adding more examples here:

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))	
}

You can find this in Go lang playground too.

答案6

得分: 0

使用JSON Unmarshal快速处理字符串**"GOTCHA"**,它会给字符串添加引号。

(示例:{"first_name":" I have whitespace "}的字符串值将转换为"\" I have whitespace \""

在修剪任何内容之前,您需要先删除额外的引号:

playground示例

// ScrubString是一个可能包含需要清除的空格的字符串。
type ScrubString string

// UnmarshalJSON从有效的json字符串中清除空格(如果有)。
func (s *ScrubString) UnmarshalJSON(data []byte) error {
	ns := string(data)
	// 确保我们没有一个空字符串 "\"\"\"".
	if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
		*s = ""
		return nil
	}
	// 删除添加的引号。
	ns, err := strconv.Unquote(ns)
	if err != nil {
		return err
	}
	// 现在我们可以修剪空格。
	*s = ScrubString(strings.TrimSpace(ns))

	return nil
}
英文:

A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.

(example: the string value of {"first_name":" I have whitespace "} will convert to "\" I have whitespace \"")

Before you can trim anything, you'll need to remove the extra quotes first:

playground example

// 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

我对性能很感兴趣,所以我对只修剪左侧的情况进行了比较:

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")
   }
}

TrimLeftFuncIndexFunc 是相同的,而 TrimLeft 较慢:

BenchmarkTrimLeftFunc-12        10325200               116.0 ns/op
BenchmarkIndexFunc-12           10344336               116.6 ns/op
BenchmarkTrimLeft-12             6485059               183.6 ns/op
英文:

I was interested in performance, so I did a comparison of just trimming the left
side:

package main

import (
   &quot;strings&quot;
   &quot;testing&quot;
)

var s = strings.Repeat(&quot;A&quot;, 63) + &quot;B&quot;

func BenchmarkTrimLeftFunc(b *testing.B) {
   for n := 0; n &lt; b.N; n++ {
      _ = strings.TrimLeftFunc(s, func(r rune) bool {
         return r == &#39;A&#39;
      })
   }
}

func BenchmarkIndexFunc(b *testing.B) {
   for n := 0; n &lt; b.N; n++ {
      i := strings.IndexFunc(s, func(r rune) bool {
         return r != &#39;A&#39;
      })
      _ = s[i]
   }
}

func BenchmarkTrimLeft(b *testing.B) {
   for n := 0; n &lt; b.N; n++ {
      _ = strings.TrimLeft(s, &quot;A&quot;)
   }
}

TrimLeftFunc and IndexFunc are the same, with TrimLeft being slower:

BenchmarkTrimLeftFunc-12        10325200               116.0 ns/op
BenchmarkIndexFunc-12           10344336               116.6 ns/op
BenchmarkTrimLeft-12             6485059               183.6 ns/op

答案8

得分: -1

正如 @Kabeer 提到的那样,你可以使用 TrimSpace 函数。这里是来自 Go 语言文档的一个示例:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

TrimSpace 函数可以去除字符串开头和结尾的空白字符,包括空格、制表符和换行符。以上示例会输出 "Hello, Gophers"。

英文:

Just as @Kabeer has mentioned, you can use TrimSpace and here is an example from golang documentation:

package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func main() {
	fmt.Println(strings.TrimSpace(&quot; \t\n Hello, Gophers \n\t\r\n&quot;))
}

huangapple
  • 本文由 发表于 2014年3月27日 20:43:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/22688010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定