Go Strings

From Wiki
Jump to navigation Jump to search

back to Go Basics

text1 := "\"what's that?\", he said" // Interpreted string literal
text2 := `"what's that?", he said`   // Raw string literal
radicals := "√ \u221A \U0000221a"    // radicals == "√ √ √"
book := "The Spirit Level" +                     // String concatenation
        " by Richard Wilkinson"
book += " and Kate Pickett"                      // String append
fmt.Println("Josey" < "José", "Josey" == "José") // String comparisons


Efficient String Append

var buffer bytes.Buffer
for {
    if piece, ok := getNextValidString(); ok {
        buffer.WriteString(piece)
    } else {
        break
    }
}
fmt.Print(buffer.String(), "\n")


Anatomy of a string

s := "naïve"
fmt.Println(s, len(s))     // prints "naïve 6"


Slicing Strings

line := "røde og gule sløjfer"
i := strings.Index(line, " ")     // Get the index of the first space
firstWord := line[:i]             // Slice up to the first space
j := strings.LastIndex(line, " ") // Get the index of the last space
lastWord := line[j+1:]            // Slice from after the last space
fmt.Println(firstWord, lastWord)  // Prints: røde sløjfer


Anatomy of a string with whitespace

line := "rå tørt\u2028vær"
i := strings.IndexFunc(line, unicode.IsSpace)     // i == 3
firstWord := line[:i]
j := strings.LastIndexFunc(line, unicode.IsSpace) // j == 9
_, size := utf8.DecodeRuneInString(line[j:])      // size == 3
lastWord := line[j+size:]                         // j + size == 12
fmt.Println(firstWord, lastWord)                  // Prints: rå vær


fmt print functions

fmt.Errorf(format,args...)	         // Returns an error value containing a string 
fmt.Fprint|Fprintf|Fprintln(writer, ...) // Writes to writer
fmt.Print|Printf|Println(args...)        // Writes to os.Stdout
fmt.Sprint|Sprintf|Sprintln(args...)     // Returns a string
/* Xprint(args...)            concatenate args */
/* Xprintf(format, args...)   print using format */
/* Xprintln(args...)          print args separated by spaces, ending with newline */

All versions return number of bytes written, and an error or nil.


fmt format specifiers

fmt.Printf("%t %t\n", true, false)                           // true false
fmt.Printf("|%b|%9b|%-9b|%09b|% 9b|\n", 37, 37, 37, 37, 37)  // |100101|···100101|100101···|000100101|···100101|
fmt.Printf("|%o|%#o|%# 8o|%#+ 8o|%+08o|\n", 41, 41, 41, 41, -41)  // |51|051|·····051|····+051|-0000051|
i := 3931
fmt.Printf("|%x|%X|%8x|%08x|%#04X|0x%04X|\n", i, i, i, i, i, i)  // |f5b|F5B|·····f5b|00000f5b|0X0F5B|0x0F5B|
i = 569
fmt.Printf("|$%d|$%06d|$%+06d|\n", i, i, i)  // |$569|$000569|$+00569|
fmt.Printf("%d %#04x %U '%c'\n", 0x3A6, 934, '\u03A6', '\U000003A6')  // 934·0x03a6·U+03A6·'Φ'
x = 7194.84
fmt.Printf("%e %f %g\n", x, x, x)                 // 7.194840e+03 7194.840000 7194.84
fmt.Printf("%2.4f \n", x)                         // 7194.8400
fmt.Printf("%s %q \n", "hi", "billy")             // hi "billy"
fmt.Printf("|%10s|%-10s|\n", "billy", "billy")    // |     billy|billy     |
fmt.Printf("%T, %T, %T\n", "billy", true, 24.35)  // string, bool, float64
s := "billy"
fmt.Printf("%s's pointer is %p\n", s, &s)         // billy's pointer is 0xf840028220


strings package

fmt.Println(strings.Contains("abcdefg", "cd"))           // true
fmt.Println(strings.Count("abcdefg", "cd"))              // 1
fmt.Println(strings.Fields("abc def\tghi"))              // [abc def ghi]
fmt.Println(strings.Index("abcdefg", "cd"))              // 2
fmt.Println(strings.IndexAny("abcdefg", "eb"))           // 1
fmt.Println(strings.Join([]string{"a", "b", "c"}, "|"))  // a|b|c
fmt.Println(strings.IndexAny("abcdefg", "eb"))           // 1
fmt.Println(strings.Repeat("*=*", 4))                    // *=**=**=**=*
fmt.Println(strings.Replace("abcdefg", "cd", "dc", -1))  // abdcefg
fmt.Println(strings.Split("abcdefg", "e"))               // [abcd fg]
fmt.Println(strings.Title("abcdefg"))                    // Abcdefg
fmt.Println(strings.ToUpper("abcdefg"))                  // ABCDEFG
fmt.Println(strings.Trim("abcdefg", "ag"))               // bcdef
fmt.Println(strings.TrimSpace("   abcdefg   "))          // abcdefg


strconv package

fmt.Println(strconv.Atoi("14256"))             // 14256 <nil>
fmt.Println(strconv.FormatBool(false))         // false
fmt.Println(strconv.FormatInt(14256, 16))      // 37b0
fmt.Println(strconv.Itoa(14256))               // 14256
fmt.Println(strconv.ParseBool("T"))            // true <nil>
fmt.Println(strconv.ParseInt("14256", 10, 0))  // 14256 <nil>