Pattern Finder
Part of the Fundamentals section of Coddy's Swift journey — lesson 85 of 86.
Challenge
EasyRead two lines of input: the first line is the text to search through, and the second line is the pattern to find.
Count how many times the pattern appears in the text, including overlapping occurrences, and print the count.
Requirements:
- Read the text string from the first line of input
- Read the pattern string from the second line of input
- Iterate through the text and check for the pattern at each position
- Count all occurrences, including overlapping matches
- Print the total count as a single integer
Hint: To extract a substring starting at index i with a specific length, you can use string slicing with indices. Convert the string to an array of characters or use Swift's string index manipulation to check if the pattern matches at each position.
Example:
If the input is:
ababa
abaThe output should be:
2The pattern "aba" appears at index 0 and index 2 in "ababa".
Try it yourself
// Read input
let text = readLine()!
let pattern = readLine()!
// TODO: Write your code below
// Count how many times the pattern appears in the text (including overlapping occurrences)
// Output the result
print(count)All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input