What You’ll Build
A search program that:- Contains a predefined text corpus
- Accepts multiple search words as command-line arguments
- Finds the first occurrence of each word
- Reports the position number of each match
- Uses nested loops with
breakstatements
What You’ll Learn
- Splitting strings into words with
strings.Fields - Nested loop structures
- Using
breakto exit loops early - Iterating over string slices
- Command-line argument processing
- Formatting output with
fmt.Printf
Complete Implementation
How It Works
Running the Program
Understanding the Output Format
#- Literal hash character%-2d- Left-aligned integer, minimum 2 characters wide:- Literal colon and space%q- Quoted string (adds double quotes)\n- Newline
Key Concepts
strings.Fields Function
strings.Fields Function
Nested Loops with Break
Nested Loops with Break
break only exits the innermost loop.Range Over Slices
Range Over Slices
Printf Format Specifiers
Printf Format Specifiers
Algorithm Flow
Enhancements to Try
- Show all occurrences - Don’t break, show every match
- Case-insensitive search - Match “Cat”, “CAT”, “cat”
- Count occurrences - Report how many times each word appears
- Search in file - Read corpus from a text file
- Partial matches - Find words containing the query
- Context - Show surrounding words
- Regular expressions - Use regex for complex patterns
- Highlighted output - Color-code the matches
Show All Occurrences
Remove thebreak to find all matches:
again:
Case-Insensitive Search
Count Occurrences
Search in File
Real-World Applications
- Log analysis - Search for keywords in log files
- Text indexing - Build simple search engines
- Data validation - Check if required words exist
- Code search - Find variable/function names
- Document processing - Extract specific terms
Performance Considerations
Next Steps
Lucky Number Game
Practice loops with randomization
Strings Guide
Master string operations