查找一个字符串是否是 SML NJ 中其他字符串的子字符串
在 SML NJ 中,我想查找一个字符串是否是另一个字符串的子字符串并找到它的索引。有人可以帮我解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Substring.position
函数是我在基础库中找到的唯一一个似乎可以进行字符串搜索的函数。不幸的是,Substring
模块有点难以使用,所以我编写了以下函数来使用它。只需传递两个字符串,它就会返回一个option
:如果未找到,则返回NONE
;如果找到,则返回索引的SOME
:The
Substring.position
function is the only one I can find in the basis library that seems to do string search. Unfortunately, theSubstring
module is kind of hard to use, so I wrote the following function to use it. Just pass two strings, and it will return anoption
:NONE
if not found, orSOME
of the index if it is found:好吧,您拥有所有子字符串函数,但是如果您还想知道它的位置,那么最简单的方法就是通过线性扫描自己完成。
基本上,您想要分解两个字符串,然后将要查找的子字符串的第一个字符与源字符串的每个字符进行比较,每次失败时都会增加位置计数器。当您找到匹配项时,您也会移动到子字符串中的下一个字符,而不移动位置计数器。如果子字符串为“空”(当您留下空列表时建模),您已将其全部匹配并且可以返回位置索引,但是如果匹配突然失败,您必须返回到第一个匹配时并且跳过一个字母(增加位置计数器)并重新开始。
希望这可以帮助您开始自己做这件事。
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.