UP | HOME

Go: String-related packages

Table of Contents

1 Strings

names := "Niccolò•Noël•Geoffrey•Amélie••Turlough•José"
fmt.Print("|")
for _, name := range strings.Split(names, "•") {
fmt.Printf("%s|", name)
}
fmt.Println()
|Niccolò|Noël|Geoffrey|Amélie||Turlough|José|

for _, record := range []string{
        "László Lajtha*1892*1963",
        "Édouard Lalo\t1823\t1892",
        "José Ángel Lamas|1775|1814"} {
                fmt.Println(strings.FieldsFunc(record, func(char rune) bool {
                        switch char {
                        case '\t', '*', '|':
                                return true
                        }
                        return false
                }))
        }
[László Lajtha 1892 1963]
[Édouard Lalo 1823 1892]
[José Ángel Lamas 1775 1814]

names := " Antônio\tAndré\tFriedrich\t\t\tJean\t\tÉlisabeth\tIsabella \t"
names = strings.Replace(names, "\t", " ", -1)
fmt.Printf("|%s|\n", names)
| Antônio André Friedrich   Jean  Élisabeth Isabella  |

asciiOnly := func(char rune) rune {
        if char > 127 {
                return '?'
        }
        return char
}
fmt.Println(strings.Map(asciiOnly, "Jérôme Österreich"))
J?r?me ?sterreich

2 Strconv

for _, truth := range []string{"1", "t", "TRUE", "false", "F", "0", "5"} {
        if b, err := strconv.ParseBool(truth); err != nil {
                fmt.Printf("\n{%v}", err)
        } else {
                fmt.Print(b, " ")
        }
}
true true true false false false
{strconv.ParseBool: parsing "5": invalid syntax}

i := 16769023
fmt.Println(strconv.Itoa(i))
fmt.Println(strconv.FormatInt(int64(i), 10))
fmt.Println(strconv.FormatInt(int64(i), 2))
fmt.Println(strconv.FormatInt(int64(i), 16))
16769023
16769023
111111111101111111111111
ffdfff

s := "Alle ønsker å være fri."
quoted := strconv.Quote(s)
fmt.Println(quoted)
fmt.Println(strconv.Unquote(quoted))
Alle ønsker å være fri.

3 Utf8 and the unicode

  • The unicode/utf8 package provides several useful functions for querying and manipulating strings and []byte s which hold UTF-8 bytes.
  • The unicode package provides functions for querying Unicode code points to determine if they meet certain criteria—for example, whether the character they represent is a digit or a lowercase letter.

4 Regexp

The regexp package is a Go implementation of Russ Cox’s RE2 regular expression engine. ✪ This engine is fast and thread-safe. The RE2 engine doesn’t use backtracking, so guarantees linear time execution \(O(n)\) where \(n\) is the length of the matched string, whereas backtracking engines can easily take exponential time \(O(2)\). The superior performance is gained at the expense of having no support for backreferences in searches.

Author: Pavel Vavilin

Created: 2017-11-11 Sat 02:59

Validate