Golang: String Functions

By Xah Lee. Date: . Last updated: .

Length (Number of Bytes)

len(string)
Return 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]
Return 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 Table]

Join String

Use + to join string. example:

"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/ [see Golang: Slice]

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

Golang

Examples

Reference