Hoe voorloop- en volgspaties van een tekenreeks bijsnijden?

Wat is de effectieve manier om de voorloop- en volgspaties van de tekenreeksvariabele in Go in te korten?


Antwoord 1, autoriteit 100%

strings.TrimSpace(s)

Bijvoorbeeld

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

Uitvoer:

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

Antwoord 2, autoriteit 11%

Er zijn een heleboel functies om strings in go te trimmen.

Zie ze daar: Trim

Hier is een voorbeeld, aangepast vanuit de documentatie, waarbij voorloop- en volgspaties worden verwijderd:

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

Antwoord 3, autoriteit 3%

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

Uitvoer:
Hallo, Gophers

En volg gewoon deze link – https://golang.org/pkg/strings/#TrimSpace


Antwoord 4, autoriteit 2%

Voor het trimmen van je string heeft het “strings”-pakket van Go de functie TrimSpace(), Trim()die voorloop- en volgspaties bijsnijdt.

Bekijk de documentatievoor meer informatie.


Antwoord 5

Zoals @Kabeer al zei, kun je TrimSpace gebruiken en hier is een voorbeeld uit de golang-documentatie:

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

Antwoord 6

@peterSO heeft het juiste antwoord. Ik voeg hier meer voorbeelden toe:

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

Je kunt dit ook vinden in Go lang-speeltuin.


Antwoord 7

Een snelle string “GOTCHA”met JSON Unmarshall die aanhalingstekens zal toevoegen aan strings.

(voorbeeld:de tekenreekswaarde van {"first_name":" I have whitespace "}wordt omgezet in "\" I have whitespace \"")

Voordat je iets kunt inkorten, moet je eerst de extra aanhalingstekens verwijderen:

voorbeeld speeltuin

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

Antwoord 8

Ik was geïnteresseerd in prestaties, dus ik deed een vergelijking door alleen de linkerkant bij te snijden
kant:

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

TrimLeftFuncen IndexFunczijn hetzelfde, waarbij TrimLeftlangzamer is:

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

Other episodes