🧵 Go Strings – Length, Concatenation, Comparison, Substrings & More
🧲 Introduction – Why Master Strings in Go?
Strings are everywhere—from handling user input and API responses to parsing logs or filenames. Go treats strings as immutable UTF-8 sequences, offering built-in tools for concatenation, slicing, replacing, comparing, and even parsing date strings using packages like strings, strconv, and time.
🎯 In this guide, you’ll learn:
- How to measure string length, concatenate, and compare
- How to split and extract substrings
- How to replace text and interpolate variables
- How to parse dates from string formats
📘 Topics Covered
| 🔹 Concept | 📖 Description |
|---|---|
| 📏 Go String Length | Count characters or bytes in a string |
| ➕ Go Concatenation | Join strings using + or fmt.Sprintf |
| 🔍 Go Compare Strings | Use equality and relational operators |
| ✂️ Go Split String | Split strings into slices based on a delimiter |
| 🔎 Go Substring Extraction | Extract parts of strings using slicing syntax |
| 🧽 Go String Replacement | Replace substrings using strings.Replace or ReplaceAll |
| 💬 Go String Interpolation | Insert variables into strings with fmt.Sprintf or formatting methods |
| 🕒 Go Parse Date Strings | Convert string-based dates into time.Time values using time.Parse |
📏 Go – String Length
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Gopher"
fmt.Println(len(s)) // Bytes
fmt.Println(utf8.RuneCountInString(s)) // Characters
}
✅ Use len() for byte count, utf8.RuneCountInString() for character count.
➕ Go – String Concatenation
s1 := "Go"
s2 := "Lang"
result := s1 + " " + s2
fmt.Println(result)
✅ With formatting:
msg := fmt.Sprintf("Welcome to %s version %d", "Go", 1)
fmt.Println(msg)
🔍 Go – Compare Strings
a := "apple"
b := "banana"
fmt.Println(a == b) // false
fmt.Println(a < b) // true (lexicographically)
✅ Go strings can be compared using ==, !=, <, >.
✂️ Go – Split String
import "strings"
text := "red,green,blue"
colors := strings.Split(text, ",")
fmt.Println(colors) // [red green blue]
✅ Use strings.Fields() to split by whitespace.
🔎 Go – Substring Extraction
s := "Golang"
sub := s[0:3]
fmt.Println(sub) // "Gol"
✅ Use slicing s[start:end] to extract substrings.
⚠️ Be cautious: indexing operates on bytes, not characters.
🧽 Go – String Replacement
import "strings"
original := "hello world"
replaced := strings.Replace(original, "world", "Go", 1)
fmt.Println(replaced) // "hello Go"
✅ Replace all:
strings.ReplaceAll("a-b-a", "a", "x") // "x-b-x"
💬 Go – String Interpolation
name := "Alice"
age := 30
message := fmt.Sprintf("Name: %s, Age: %d", name, age)
fmt.Println(message)
✅ Use fmt.Sprintf() for flexible formatting and variable insertion.
🕒 Go – Parse Date Strings
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02"
str := "2025-06-07"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println("Parse error:", err)
} else {
fmt.Println("Parsed date:", t)
}
}
✅ layout must match Go’s reference date: "Mon Jan 2 15:04:05 MST 2006".
📌 Summary – Recap & Next Steps
Go’s string handling is both simple and powerful. Whether you’re splitting user input, comparing responses, or formatting log output, Go’s standard libraries give you clean, immutable, and performant string manipulation tools.
🔍 Key Takeaways:
- Use
len()for bytes,utf8for rune (character) count - Concatenate with
+orfmt.Sprintf - Use
stringsfor splitting, replacing, and trimming - Be careful with slicing multibyte strings (UTF-8)
- Parse date strings using
time.Parseand fixed layout formats
⚙️ Real-World Applications:
- Building REST APIs with query parameter parsing
- Logging formatted messages with variable interpolation
- Parsing CSV or configuration files
- Reading and formatting date strings from user input
❓ Frequently Asked Questions
❓ How do I count characters in a UTF-8 string in Go?
✅ Use utf8.RuneCountInString(str) from unicode/utf8.
❓ Can I mutate a string in Go?
✅ ❌ No. Strings are immutable. You must create a new string.
❓ What is the safest way to slice strings containing emojis or non-ASCII characters?
✅ Convert to []rune before slicing:
runes := []rune("🙂😎")
fmt.Println(string(runes[0:1]))
❓ How do I format strings with numbers in Go?
✅ Use fmt.Sprintf():
s := fmt.Sprintf("Count: %d", 10)
❓ Why does Go use 2006-01-02 for time parsing layout?
✅ It’s a hardcoded reference date that demonstrates format structure (not arbitrary).
Share Now :
