Deduplicate code and use stdlib in string functions

Also fixes some typos, compares strings in-place instead of copying a substr, and fixes style issues.
While we're at it, it should be "occurrences"