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.
Might be better as: Replace all occurrances of the character \p from in  \p str  with \p to