Bird
Raised Fist0
DSA Goprogramming

How Strings Work Differently Across Languages in DSA Go - Step-by-Step

Choose your learning style10 modes available
Mental Model
Strings are sequences of characters, but how they are stored and handled varies by language. Some use arrays of bytes, others use arrays of characters or code points.
Analogy: Think of strings like a row of mailboxes. In some places, each mailbox holds one letter (byte), in others, each mailbox holds a whole word (character), and in some, mailboxes can hold different sized letters depending on the language.
Go string: [b][y][t][e][s]
Python string: [c][h][a][r][s]
Java string: [c][h][a][r][s]

Each box holds different units depending on language.
Dry Run Walkthrough
Input: String: "Go😊" in Go, Python, and Java
Goal: Show how the same string is stored differently in each language
Step 1: Represent string "Go😊" in Go as bytes
[G][o][0xF0][0x9F][0x98][0x8A]
Why: Go stores strings as bytes, so the emoji is stored as multiple bytes (UTF-8 encoding)
Step 2: Represent string "Go😊" in Python as characters
[G][o][😊]
Why: Python strings are sequences of Unicode characters, so emoji is one character
Step 3: Represent string "Go😊" in Java as chars
[G][o][\uD83D][\uDE0A]
Why: Java uses UTF-16 encoding, so emoji is stored as two chars (surrogate pairs)
Result:
Go bytes: [G][o][0xF0][0x9F][0x98][0x8A]
Python chars: [G][o][😊]
Java chars: [G][o][\uD83D][\uDE0A]
Annotated Code
DSA Go
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	str := "Go😊"

	// Go string as bytes
	fmt.Printf("Go bytes: ")
	for i := 0; i < len(str); i++ {
		fmt.Printf("[%X]", str[i]) // print each byte in hex
	}
	fmt.Println()

	// Go string as runes (characters)
	fmt.Printf("Go runes: ")
	for _, r := range str {
		fmt.Printf("[%c]", r) // print each rune (Unicode code point)
	}
	fmt.Println()

	// Count runes
	fmt.Printf("Rune count: %d\n", utf8.RuneCountInString(str))
}
for i := 0; i < len(str); i++ {
iterate over each byte in the string
fmt.Printf("[%X]", str[i])
print each byte in hexadecimal to show raw storage
for _, r := range str {
iterate over each Unicode character (rune) in the string
fmt.Printf("[%c]", r)
print each character to show logical characters
utf8.RuneCountInString(str)
count number of Unicode characters in the string
OutputSuccess
Go bytes: [47][6F][F0][9F][98][8A] Go runes: [G][o][😊] Rune count: 3
Complexity Analysis
Time: O(n) because we must look at each byte or character once to process the string
Space: O(n) because the string storage size depends on number of bytes or characters
vs Alternative: Using bytes is more memory efficient but requires careful handling of multi-byte characters; using runes or characters is easier for logic but may use more space
Edge Cases
Empty string ""
No bytes or characters, counts as zero length
DSA Go
for i := 0; i < len(str); i++ {
String with only ASCII characters "Hello"
Bytes and characters count are the same, each character is one byte
DSA Go
utf8.RuneCountInString(str)
String with multi-byte Unicode characters "😊😊"
Bytes count is larger than character count, runes count correctly counts characters
DSA Go
for _, r := range str {
When to Use This Pattern
When you see problems involving string length or indexing in different languages, remember strings may be bytes or Unicode characters, so choose the right method to avoid bugs.
Common Mistakes
Mistake: Assuming string length equals number of characters in all languages
Fix: Use language-specific functions to count Unicode characters, not bytes
Mistake: Indexing strings by byte position and expecting characters
Fix: Use rune iteration or character indexing methods to handle multi-byte characters
Summary
Strings store sequences of characters but differ in storage as bytes or Unicode units across languages.
Use byte-level operations for raw data and character-level operations for logical text processing.
The key insight is that string length and indexing depend on encoding, so handle strings with language-aware methods.

Practice

(1/5)
1. In Go, what is the type of a string internally?
var s = "hello"
easy
A. A sequence of bytes representing UTF-8 encoded characters
B. An array of Unicode code points (runes)
C. A linked list of characters
D. A pointer to a null-terminated character array

Solution

  1. Step 1: Understand Go string representation

    Go strings are immutable sequences of bytes, typically UTF-8 encoded.
  2. Step 2: Compare with other languages

    Unlike some languages that use arrays of Unicode code points, Go uses bytes internally.
  3. Final Answer:

    A sequence of bytes representing UTF-8 encoded characters -> Option A
  4. Quick Check:

    Go strings = UTF-8 bytes [OK]
Hint: Remember Go strings are byte sequences, not rune arrays [OK]
Common Mistakes:
  • Thinking Go strings store runes directly
  • Assuming null-terminated strings like C
  • Confusing with linked list or array types
2. Which of the following is the correct way to get the length of a string in Go?
s := "hello"
easy
A. length(s)
B. s.length()
C. len(s)
D. s.len

Solution

  1. Step 1: Recall Go built-in function for length

    Go uses the built-in function len() to get the length of strings and slices.
  2. Step 2: Check other options

    Methods like s.length() or s.len do not exist in Go; length(s) is not valid syntax.
  3. Final Answer:

    len(s) -> Option C
  4. Quick Check:

    Use len() for string length in Go [OK]
Hint: Use len() function to get string length in Go [OK]
Common Mistakes:
  • Using method calls like s.length() from other languages
  • Trying to access length as a property
  • Using undefined functions like length()
3. What will be the output of this Go code?
package main
import "fmt"
func main() {
  s := "Go😊"
  fmt.Println(len(s))
}
medium
A. 3
B. 6
C. 4
D. 5

Solution

  1. Step 1: Analyze string content and encoding

    The string "Go😊" has 'G' and 'o' as 1 byte each, and the emoji '😊' is a 4-byte UTF-8 character.
  2. Step 2: Calculate total byte length

    Total bytes = 1 (G) + 1 (o) + 4 (😊) = 6 bytes.
  3. Step 3: Check len() output

    len(s) returns the number of bytes, so output is 6.
  4. Final Answer:

    6 -> Option B
  5. Quick Check:

    len() counts bytes, not characters [OK]
Hint: len() returns bytes count, not character count [OK]
Common Mistakes:
  • Assuming len() returns number of characters
  • Ignoring multi-byte UTF-8 characters
  • Confusing bytes with runes
4. Identify the error in this Go code that tries to print each character of a string:
package main
import "fmt"
func main() {
  s := "Go"
  for i := 0; i < len(s); i++ {
    fmt.Println(s[i])
  }
}
medium
A. It prints byte values, not characters
B. Syntax error in for loop
C. s[i] is invalid syntax
D. Missing import for fmt

Solution

  1. Step 1: Understand s[i] in Go strings

    Accessing s[i] returns the byte at index i, not a character or string.
  2. Step 2: Check output of fmt.Println(s[i])

    It prints the numeric byte value (ASCII code), not the character itself.
  3. Final Answer:

    It prints byte values, not characters -> Option A
  4. Quick Check:

    s[i] = byte, prints number [OK]
Hint: s[i] gives byte, convert to rune or string to print char [OK]
Common Mistakes:
  • Expecting s[i] to print characters directly
  • Ignoring byte vs rune difference
  • Assuming syntax error where none exists
5. How can you correctly iterate over each Unicode character in a Go string to print them?
Choose the correct code snippet.
hard
A. for i := 0; i < len(s); i++ { fmt.Println(string(s[i])) }
B. for i := range s { fmt.Println(s[i]) }
C. for i, c := range s { fmt.Println(s[i]) }
D. for _, r := range s { fmt.Println(string(r)) }

Solution

  1. Step 1: Understand iteration over strings in Go

    Using 'for _, r := range s' iterates over runes (Unicode code points), not bytes.
  2. Step 2: Check printing each character

    Converting rune 'r' to string prints the actual character correctly.
  3. Step 3: Analyze other options

    for i := 0; i < len(s); i++ { fmt.Println(string(s[i])) } prints bytes as strings, which may break multi-byte chars; C and D print bytes, not runes.
  4. Final Answer:

    for _, r := range s { fmt.Println(string(r)) } -> Option D
  5. Quick Check:

    Use range to get runes for correct Unicode iteration [OK]
Hint: Use 'for _, r := range s' to iterate Unicode chars [OK]
Common Mistakes:
  • Iterating by byte index instead of runes
  • Printing bytes as characters causing errors
  • Confusing index and rune variables
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard