Strings and Text
Examples in
Go
package main
import (
"fmt"
"math/rand"
"time"
)
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
func RandomString(strlen int) string {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
result := make([]byte, strlen)
for i := range result {
result[i] = chars[r.Intn(len(chars))]
}
return string(result)
}
func main() {
fmt.Println(RandomString(10))
}
Last Run
:
BFDoNyBToC
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello"
t := s + " World"
fmt.Println(t)
// Using a builder
var b strings.Builder
b.WriteString("Good")
b.WriteString("Bye\n")
fmt.Println(b.String())
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("Contains: ", strings.Contains("test", "es"))
}
Last Run
:
Contains: true
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("cheese", "e"))
fmt.Println(strings.Count("five", "")) // before & after each rune
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.HasPrefix("Gopher", "Go"))
fmt.Println(strings.HasPrefix("Gopher", "C"))
fmt.Println(strings.HasPrefix("Gopher", ""))
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.HasSuffix("Amigo", "go"))
fmt.Println(strings.HasSuffix("Amigo", "O"))
fmt.Println(strings.HasSuffix("Amigo", "Ami"))
fmt.Println(strings.HasSuffix("Amigo", ""))
}
Last Run
:
true
false
false
true
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
}
Join concatenates a list of strings to create a single string. A separator is placed between elements in the resulting string.
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
}
Last Run
:
foo, bar, baz
Creates a new string consisting of a substring repeated a certain number of times.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("ba" + strings.Repeat("na", 2))
}
Creates a string that has non overlapping instances of a substring replaced by a new string.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
}
Splits a string into substrings separated by a given separator substring.
package main
import (
"fmt"
"strings"
)
func main() {
input := `xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff`
a := strings.FieldsFunc(input, Split)
fmt.Println(a)
}
func Split(r rune) bool {
return r == ':' || r == '.'
}
Last Run
:
[xxxxx yyyyy zzz aaa bbb cc dd ee ff]
Creates a string with all Unicode letters from the original string mapped to their lower case.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToLower("Gopher"))
}
Last Run
:
gopher
Creates a string with all Unicode letters from the original string mapped to their upper case.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("Gopher"))
}
Last Run
:
GOPHER
Returns the number of characters in the string.
package main
import (
"fmt"
)
func main() {
fmt.Println(len("Gopher"))
}
package main
import (
"fmt"
)
func main() {
fmt.Println("Char:", "hello"[1])
}
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile the expression once, usually at init time.
// Use raw strings to avoid having to quote the backslashes.
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
fmt.Println(validID.MatchString("adam[23]"))
fmt.Println(validID.MatchString("eve[7]"))
fmt.Println(validID.MatchString("Job[48]"))
fmt.Println(validID.MatchString("snakey"))
}
Last Run
:
true
true
false
false
Go offers excellent support for string formatting in the printf tradition. Here are some examples of common string formatting tasks.
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
func main() {
// In these examples we use fmt.Printf to directly output the result on stdout.
// If you wanted to create a string result to be used in a different way,
// you can use fmt.Sprintf instead.
p := point{1, 2}
fmt.Printf("%v\n", p)
fmt.Printf("%+v\n", p)
fmt.Printf("%#v\n", p)
fmt.Printf("%T\n", p)
fmt.Printf("%t\n", true)
fmt.Printf("%d\n", 123)
fmt.Printf("%b\n", 14)
fmt.Printf("%c\n", 33)
fmt.Printf("%x\n", 456)
fmt.Printf("%f\n", 78.9)
fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0)
fmt.Printf("%s\n", "\"string\"")
fmt.Printf("%q\n", "\"string\"")
fmt.Printf("%x\n", "hex this")
fmt.Printf("%p\n", &p)
fmt.Printf("|%6d|%6d|\n", 12, 345)
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
fmt.Printf("|%6s|%6s|\n", "foo", "b")
fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
s := fmt.Sprintf("a %s", "string")
fmt.Println(s)
fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
package main
import (
"strings"
"fmt"
)
func main() {
s := "Some string with \n\t whitespace"
fmt.Println(strings.Join(strings.Fields(s),""))
}
package main
import (
"fmt"
"regexp"
)
func main() {
example := "#GoLangCode!$!"
// Make a Regex to say we only want letters and numbers
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
panic(err)
}
processedString := reg.ReplaceAllString(example, "")
fmt.Println(processedString)
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Compare("a", "b"))
fmt.Println(strings.Compare("a", "a"))
fmt.Println(strings.Compare("b", "a"))
}
package main
import "fmt"
func main() {
fmt.Println("string" + string('c'))
}
package main
import (
"fmt"
"strings"
)
func main() {
var b strings.Builder
for i := 3; i >= 1; i-- {
fmt.Fprintf(&b, "%d...", i)
}
b.WriteString("ignition")
fmt.Println(b.String())
}
Last Run
:
3...2...1...ignition
package main
import (
"fmt"
"strings"
)
func main() {
a := []int{1, 2, 3}
str := fmt.Sprint(a)
joined := strings.Join(strings.Split(str[1:len(str)-1], " "), "++")
fmt.Println(joined)
}
Last Run
:
1++2++3