Skip to content

Instantly share code, notes, and snippets.

@vicsstar
Last active November 6, 2015 00:13
Show Gist options
  • Save vicsstar/b3bca662b5eb4cd1adc6 to your computer and use it in GitHub Desktop.
Save vicsstar/b3bca662b5eb4cd1adc6 to your computer and use it in GitHub Desktop.
DZone :: Code Challenge Series: Substring Search
object StringFinder {
/**
* Finds the first occurrence of a substring (`query`) within a `text`.
* @param text - the text to search in.
* @param query - the substring to find in `text`.
* @param pos - position in text to start searching from.
*/
def find(text: String, query: String)(pos: Int): Unit = {
/*
* make sure `pos` hasn't gone out
* of range of what can be queried within `text`.
*/
if (pos >= 0 && pos <= text.length - query.length) {
/*
* make a substring based on extracting the characters
* from `pos` to `pos + query.length` exclusive.
*/
val subText =
(for (j <- pos until pos + query.length)
yield text.charAt(j)).mkString("")
// compare the extracted sub-text with `query`.
if (subText == query)
// let the user know `query` has been found and where.
println(s"""First occurrence of "$query" found at $pos""")
else {
/*
* so it wasn't found now, try searching
* from the next character in `text`.
*/
find(text, query)(pos + 1)
}
} else {
// `query` wasn't found in `text` at all.
println(s""""$query" doesn't exist anywhere in the text.""")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment