Limited Offer
60% OFF on all plans!

Strings in Go

Master string handling in Go: single-line and multi-line strings, formatting with fmt, indexing, traversal, searching, slicing, comparing, replacing, rune/byte conversions, and more.

Creating Strings

A string is a sequence of bytes (UTF-8 in Go). Strings can be written with double quotes. Backticks create raw string literals where escape sequences are ignored and newlines are allowed. Use fmt.Sprintf or fmt.Printf for interpolation.

1. Single-Line Strings

Use double quotes for strings. Go does not use single quotes for strings (single quotes are for runes).

2. Multi-line Strings (Raw String Literals)

Use backticks for raw string literals. Actual newlines in the source are preserved in the string.

3. String Interpolation (fmt.Sprintf)

Insert values into strings using fmt.Sprintf with format verbs.

String Basics (Indexing, Length, Traversal)

In Go, indexing a string with s[i] returns the byte at that position. The length len(s) is in bytes. To work with Unicode characters (runes), use a for range loop or convert to []rune.

1. Accessing the Character at a Specific Index

Use s[i] to get the byte at index i. For a single character as string, use string(s[i]) or work with runes.

2. Getting String Length

len(s) returns the number of bytes. For rune count, use utf8.RuneCountInString(s).

3. Traversing Through a String

Use for range to iterate over runes (Unicode code points), one per character.

Formatted Strings

Use fmt.Printf with width and alignment (e.g. %-15s, %10.2f) to build table-like output. We covered this in Console Output; here is a short reminder with a price table.

1. Formatted Table Output

Build the table as a string using fmt.Sprintf, then print that string. This shows how formatted output and string interpolation work together.

Comparing & Concatenating Strings

Use == for exact equality. Use strings.Compare for lexicographic order. Concatenate with + or strings.Join for multiple parts.

1. Comparing Two Strings (Exact Match)

Use == to compare strings for exact equality.

2. Lexicographical Comparison

Use <, > for order or strings.Compare for -1, 0, 1.

3. Concatenating Strings (+) and fmt.Sprintf

Use + to join two strings. Use fmt.Sprintf to build a string from several values.

4. Joining Multiple Strings (strings.Join)

Use strings.Join to join a slice of strings with a separator.

String Transformations

Go has strings.ToUpper, strings.ToLower, and strings.Repeat. To reverse, convert to []rune, swap, then convert back to string.

1. Reversing a String ([]rune)

Convert to []rune, reverse the slice, then convert back to string. This handles Unicode correctly.

2. Reversing a String (Loop and Prepend)

Loop over runes and build the reversed string by prepending each rune.

3. Uppercase and Lowercase

Use strings.ToUpper and strings.ToLower.

4. Repeat a String

Use strings.Repeat(s, n) to repeat s n times.

Rune and Byte Conversions

In Go, a rune is a Unicode code point (int32). Indexing a string gives a byte (uint8). Use rune literals and string(r) to convert between runes and strings.

1. Character to Code (Rune)

A rune literal like 'A' is already an int32. For a byte from a string, use s[i].

2. Code to Character (string(rune))

Convert a rune or byte to a string with string(r) or string(b).

Slicing, Splitting & Trimming

Use slice syntax s[start:end] for substrings. Use strings.Split to break a string into parts. Use strings.TrimSpace, strings.TrimLeft, strings.TrimRight (or TrimPrefix/TrimSuffix) to remove characters.

1. Slicing s[start:end]

s[start:end] returns bytes from start (inclusive) to end (exclusive). Indices are in bytes.

2. Omitted Start or End

Omit start (default 0) or end (default len(s)) in a slice.

3. Splitting a String

Use strings.Split(s, sep) to get a slice of substrings.

4. Trimming Whitespace

Use strings.TrimSpace, strings.TrimLeft, strings.TrimRight (for whitespace) or strings.Trim for a custom set. Pipes (|) in the output show where the string starts and ends so you can see the effect of trimming.

Searching & Replacing

Use strings.Contains, strings.Index, strings.LastIndex, strings.HasPrefix, strings.HasSuffix, and strings.Replace. For pattern-based replace, use regexp.

1. Checking if a String Contains a Substring

Use strings.Contains(s, substr).

2. Replace First Match (strings.Replace n=1)

strings.Replace(s, old, new, n) replaces at most n occurrences. Use 1 for first only.

3. Replace All Matches (strings.Replace n=-1)

Pass -1 to replace every occurrence.

4. Finding the Index of a Substring

Use strings.Index(s, substr). Returns -1 if not found.

5. Last Index of a Substring

Use strings.LastIndex(s, substr).

6. Check if String Starts With (strings.HasPrefix)

Use strings.HasPrefix(s, prefix).

7. Check if String Ends With (strings.HasSuffix)

Use strings.HasSuffix(s, suffix).