In SML NJ, I want to find whether a string is substring of another string and find its index. Can any one help me with this?
2 Answers
The Substring.position
function is the only one I can find in the basis library that seems to do string search. Unfortunately, the Substring
module is kind of hard to use, so I wrote the following function to use it. Just pass two strings, and it will return an option
: NONE
if not found, or SOME
of the index if it is found:
fun index (str, substr) = let
val (pref, suff) = Substring.position substr (Substring.full str)
val (s, i, n) = Substring.base suff
in
if i = size str then
NONE
else
SOME i
end;

- 139,698
- 36
- 220
- 238

- 119,665
- 29
- 163
- 224
Well you have all the substring functions, however if you want to also know the position of it, then the easiest is to do it yourself, with a linear scan.
Basically you want to explode both strings, and then compare the first character of the substring you want to find, with each character of the source string, incrementing a position counter each time you fail. When you find a match you move to the next char in the substring as well without moving the position counter. If the substring is "empty" (modeled when you are left with the empty list) you have matched it all and you can return the position index, however if the matching suddenly fail you have to return back to when you had the first match and skip a letter (incrementing the position counter) and start all over again.
Hope this helps you get started on doing this yourself.

- 5,944
- 23
- 31