String Comparison: Character-by-Character
What you'll learn: How computers determine which string comes "before" or "after" another by comparing characters one-by-one in alphabetical order.
The Core Idea
When you compare two strings, the computer doesn't magically know which one is "bigger" or "smaller." Instead, it walks through both strings simultaneously, comparing characters at matching positions until it finds a difference or reaches the end.
Think of it like a dictionary: to see if "apple" comes before "apricot," you check letter-by-letter. Both start with 'a', 'p'—still matching. At position 2, you find 'p' vs 'r'. Since 'p' comes before 'r' alphabetically, "apple" comes first.
How Character-by-Character Comparison Works
The process follows these steps:
- Start at index 0 of both strings
- Compare the characters at the current position
- If they differ, the string with the "smaller" character (earlier in alphabetical order) comes first
- If they match, move to the next index and repeat
- If one string ends while the other continues, the shorter string comes first
Understanding Lexicographic Order
"Lexicographic" is the fancy term for dictionary-style ordering. Each character has a numeric value (like 'A' = 65, 'a' = 97 in ASCII), so comparison actually uses these numbers. Uppercase letters come before lowercase ones because their values are smaller.
Examples:
- "cat" < "dog" (because 'c' < 'd')
- "car" < "card" (shorter string comes first when all characters match)
- "Zoo" < "apple" (uppercase 'Z' < lowercase 'a' in ASCII ordering)
Key Takeaway: String comparison examines characters sequentially from left to right, using alphabetical (ASCII) ordering to determine which string comes first, stopping as soon as a difference is found or one string ends.