Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Task 1 — Manual Substring Search

Objective

Create a function that manually finds every occurrence of one string inside another string.

The function must return the starting index of every match.

Built-in or standard-library substring-search functions must not be used.

Input

The source string is:

s1 := "abc bca cba acb abc bca cba acb"

The search value is:

s2 := "cba"

Function

Create a function named:

FindMatch(...)

Conceptually:

FindMatch(s1, s2 string)

returns:

[]int

Search Rules

The function must scan s1 and determine every position where the complete value of s2 begins.

A match is valid only when all characters from s2 match consecutive characters in s1.

Example

The source contains:

abc bca cba acb abc bca cba acb
        ^               ^

The value:

cba

starts at indexes:

8
24

Expected Result

[]int{8, 24}

Zero-Based Indexing

Indexes are zero-based.

The first character in the source is:

index 0

Therefore, the first "cba" begins at:

index 8

Overlapping Matches

The implementation should support overlapping matches.

For example:

source = "aaaa"
search = "aa"

contains matches beginning at:

0
1
2

Therefore, after finding a match, the search should not automatically skip the entire matched substring unless the task explicitly requires non-overlapping matching.

Empty Search Value

An empty search string creates an ambiguous matching rule.

For this task, an empty search value should be rejected or return an error rather than being treated as matching every position.

Requirements

The function must:

  1. scan the source string manually
  2. compare the search value character by character
  3. identify every complete match
  4. store the starting index of every match
  5. return the indexes as []int

Restricted Operations

Do not use string-search helpers equivalent to:

Index
Contains
Find
Match
regular expressions

The matching algorithm must be implemented manually.

Implementation Notes

A straightforward implementation may treat every valid source position as a possible match start.

For each candidate position:

compare source[i + j] with search[j]

until either:

  • all search characters match
  • or a mismatch is found

The implementation should work for source and search strings other than the provided example.

Scalionix Docs

Keyboard Shortcuts

Navigate the documentation without leaving the keyboard.
Navigation
Previous subject
←
Next subject
→
Previous subsection
Alt + ↑
Next subsection
Alt + ↓
Interface
Documentation Home
Ctrl + Enter
Search
Alt + Q
Open shortcuts
?
Close dialog
Esc
Scalionix Docs

Search Documentation