Golang: String Functions

By Xah Lee. Date: . Last updated: .

Length (Number of Bytes)

len(string) → returns the number of bytes in string.

package main

import "fmt"

func main() {
	fmt.Printf("%v\n", len("abc")) // 3
	fmt.Printf("%v\n", len("ab♥")) // 5
}

SubString

s[n:m] → returns a substring of s from index n to m (excluding m). The return value's type is string.

package main

import "fmt"

func main() {

	var x = "012345"

	// substring
	fmt.Printf("%#v\n", x[2:3]) // "2"

	fmt.Printf("%#v\n", x[2:4]) // "23"

	fmt.Printf("%#v\n", x[2:2]) // ""

}

Remember, string is a sequence of bytes. So, if you have non-ASCII unicode in string, arbitrary index range may create a string that's not a sequence of characters.

package main

import "fmt"

func main() {

	const x = "♥♥♥"

	fmt.Printf("%#v\n", x[2:4]) // "\xa5\xe2"

}

[see Golang: String, Byte Slice, Rune Slice]

[see ASCII Characters ␀ ␣ ¶]

Join String

Use + to join string. e.g.

"abc" + "def"

package main

import "fmt"

func main() {
	fmt.Printf("%v\n", "a"+"b") // ab
}

Embed Expression in String?

There is no embeding expression in string. (as in Ruby or JavaScript)

The closest is this:

fmt.Sprintf("Name: %v\nAge: %v", "John", 10)

package main

import "fmt"

func main() {

	var name = "John"
	var age = 30

	var x = fmt.Sprintf("Name: %v, Age: %v", name, age)

	fmt.Println(x) // Name: John, Age: 30
}

String Functions

String functions are in package “strings”.

see https://golang.org/pkg/strings/

If your string is a byte slice, use package bytes https://golang.org/pkg/bytes/

Here's some example.

package main

import "fmt"
import "strings"

var pl = fmt.Println

func main() {

	pl("ab" == "ab") // 0

	pl(strings.Contains("abcd", "bc"))  // true
	pl(strings.HasPrefix("abca", "ab")) // true
	pl(strings.HasSuffix("abca", "ca")) // true

	pl(strings.ToLower("ABC") == "abc") // true

	pl(strings.Trim(" abc ", " ") == "abc") // true

	pl(strings.Count("abcaab", "ab") == 2) // true

	pl(strings.Index("abc", "bc") == 1) // true

	pl(strings.Join([]string{"a", "and", "b"}, " ") == "a and b") // true

	// split into slice
	pl(strings.Split("a b c", " ")) // [a b c]
}

Find Replace

Use the regex package.

See: Golang: regexp

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. String Functions
  8. Print String
  9. String Backslash Escape
  10. Rune
  11. Variable
  12. Zero Value
  13. Constant
  14. If Then Else
  15. Switch/Case
  16. Loop
  17. Basic Types
  18. Array
  19. Slice
  20. Map
  21. Struct
  22. Function
  23. Closure
  24. Pointer
  25. String, Byte Slice, Rune Slice
  26. regexp
  27. Read File
  28. Write to File
  29. Walk Dir
  30. Check File Exist
  31. System Call
  32. Get Script Path
  33. Defer
  34. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec