Movatterモバイル変換


[0]ホーム

URL:


Go string handling overview [cheat sheet]

yourbasic.org/golang

String literals (escape characters)

ExpressionResultNote
""Default zero value for typestring
"Japan 日本"Japan 日本Go code isUnicode text encoded in UTF‑8
"\xe6\x97\xa5"\xNN specifies a byte
"\u65E5"\uNNNN specifies a Unicode value
"\\"\Backslash
"\"""Double quote
"\n"Newline
"\t"Tab
`\xe6`\xe6Raw string literal*
html.EscapeString("<>")&lt;&gt;HTML escape for<, >, &, ' and "
url.PathEscape("A B")A%20BURL percent-encodingnet/url

* In`` string literals, text is interpreted literally andbackslashes have no special meaning.SeeEscapes and multiline strings for more on raw strings, escape characters and string encodings.

Concatenate

ExpressionResultNote
"Ja" + "pan"JapanConcatenation

Performance tips
See3 tips for efficient string concatenationfor how to best use a string builder to concatenate strings without redundant copying.

Equal and compare (ignore case)

ExpressionResultNote
"Japan" == "Japan"trueEquality
strings.EqualFold("Japan", "JAPAN")trueUnicode case folding
"Japan" < "japan"trueLexicographic order

Length in bytes or runes

ExpressionResultNote
len("日")3Length in bytes
utf8.RuneCountInString("日")1in runesunicode/utf8
utf8.ValidString("日")trueUTF-8?unicode/utf8

Index, substring, iterate

ExpressionResultNote
"Japan"[2]'p'Byte at position 2
"Japan"[1:3]apByte indexing
"Japan"[:2]Ja
"Japan"[2:]pan

A Gorange loop iterates over UTF-8 encoded characters (runes):

for i, ch := range "Japan 日本" {fmt.Printf("%d:%q ", i, ch)}// Output: 0:'J' 1:'a' 2:'p' 3:'a' 4:'n' 5:' ' 6:'日' 9:'本'

Iterating over bytes produces nonsense characters for non-ASCII text:

s := "Japan 日本"for i := 0; i< len(s); i++ {fmt.Printf("%q ", s[i])}// Output: 'J' 'a' 'p' 'a' 'n' ' ' 'æ' '\u0097' '¥' 'æ' '\u009c' '¬'

Search (contains, prefix/suffix, index)

ExpressionResultNote
strings.Contains("Japan", "abc")falseIs abc in Japan?
strings.ContainsAny("Japan", "abc")trueIs a, b or c in Japan?
strings.Count("Banana", "ana")1Non-overlapping instances of ana
strings.HasPrefix("Japan", "Ja")trueDoes Japan start with Ja?
strings.HasSuffix("Japan", "pan")trueDoes Japan end with pan?
strings.Index("Japan", "abc")-1Index of first abc
strings.IndexAny("Japan", "abc")1a, b or c
strings.LastIndex("Japan", "abc")-1Index of last abc
strings.LastIndexAny("Japan", "abc")3a, b or c

Replace (uppercase/lowercase, trim)

ExpressionResultNote
strings.Replace("foo", "o", ".", 2)f..Replace first two “o” with “.” Use -1 to replace all
f := func(r rune) rune {
    return r + 1
}
strings.Map(f, "ab")
bcApply function to each character
strings.ToUpper("Japan")JAPANUppercase
strings.ToLower("Japan")japanLowercase
strings.Title("ja pan")Ja PanInitial letters to uppercase
strings.TrimSpace(" foo\n")fooStrip leading and trailing white space
strings.Trim("foo", "fo")Stripleading and trailing f:s and o:s
strings.TrimLeft("foo", "f")ooonly leading
strings.TrimRight("foo", "o")fonly trailing
strings.TrimPrefix("foo", "fo")o
strings.TrimSuffix("foo", "o")fo

Split by space or comma

ExpressionResultNote
strings.Fields(" a\t b\n")["a" "b"]Remove white space
strings.Split("a,b", ",")["a" "b"]Remove separator
strings.SplitAfter("a,b", ",")["a," "b"]Keep separator

Join strings with separator

ExpressionResultNote
strings.Join([]string{"a", "b"}, ":")a:bAdd separator
strings.Repeat("da", 2)dada2 copies of “da”

Format and convert

ExpressionResultNote
strconv.Itoa(-42)"-42"Int to string
strconv.FormatInt(255, 16)"ff"Base 16

Sprintf

Thefmt.Sprintf functionis often your best friend when formatting data:

s := fmt.Sprintf("%.4f", math.Pi)// s == "3.1416"

Thisfmt cheat sheetcovers the most common formatting flags.

Regular expressions

For more advanced string handling, see thisRegular expressions tutorial,a gentle introduction to theregexp package with cheat sheetand plenty of examples.

Related

Runes and character encoding
A rune is a type meant to represent a Unicode code point. Strings, however, are sequences of bytes (typically containing Unicode text encoded in UTF-8).
yourbasic.org
Strings, bytes, runes and characters in Go
The Go Blog
Efficient string concatenation [full guide]
Use a strings.Builder together with the fmt package for a clean and simple way to build strings efficiently without redundant copying.
yourbasic.org

Most Read

See all 178 Go articles


[8]ページ先頭

©2009-2025 Movatter.jp