Post by Torben Ãgidius MogensenPost by e***@yahoo.comHow would you find the location of a string within another string?
For example,
find "foo" "don't be foolish"
would yield 9.
I'm using Moscow ML.
I don't think this function is standard in the library, so you will
inString s1 "" = ~1 (* if not found, return -1 *)
inString s1 s2 = if String.isPrefix s1 s2 then 0 (* found! *)
else (* try rest of string *)
case inString s1 (String.substring
(s2,1,String.size s2 - 1))
of
~1 => ~1 (* if not found, return -1 *)
| n => n+1 (* otherwise, add 1 to position *)
A call to inString s1 s2 will take O(|s1| * |s2|^2) time in the worst
case, but it is not hard to make a version that runs in O(|s1| * |s2|),
and with some effort, you can get O(|s1| + |s2|).
Torben
Thanks. That's what I thought. So you have to use regular
expressions
to search a string, unless you want to write your own search function.
(This seems to be true of OCaml as well.) I'm surprised that this
isn't considered a standard feature for any high-level language.
FreeBasic:
? instr( "pass by there", "by" )
awk:
print index( "pass by there", "by" )
FreePascal:
writeln( pos( "by", "pass by there" ) );
Ruby:
p "pass by there".index( "by" )
By the way, Moscow's regular expression engine is more sophisticated
than OCaml's.
Moscow has X{m,n}, which matches X at least m times and at most n
times.
In OCaml, ^ always matches after a newline; in Moscow, this behavior
is switchable. Moscow has [[:alnum:]] to match a letter or digit.
The one advantage that I can find for OCaml is \b, which matches
a word boundary.