Golang: String Functions

By Xah Lee. Date: . Last updated: .

Length (Number of Bytes)

len(string)
Return the number of bytes in string. (if you want number of characters, use utf8.RuneCountInString. See Golang: String, Byte Slice, Rune Slice )
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 (technically a byte sequence) 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. [see ASCII Characters]

package main

import "fmt"

func main() {
	const x = "♥♥♥"
	fmt.Printf("%#v\n", x[0])   // 0xe2
	fmt.Printf("%#v\n", x[2:4]) // "\xa5\xe2"
}

Join String

Use + to join string. example:

"abc" + "def"

package main

import "fmt"

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

Template String?

There is no embeding expression in string such as in Ruby "#{2+3}" [see Ruby: Formatting String] or JavaScript `${2+3}` [see JavaScript: Template String] . The closest is fmt.Sprintf.

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

[see Golang: Convert Value to String]

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 String

Golang

Compile and Run

String

Types and Values

Branching and Loop

Data Structure

Function

Misc

Examples

Reference