F#计算子字符串在一个字符串中包含多少次 [英] F# Count how Many times a substring Contains within a string
问题描述
如何计算一个子字符串在一个字符串中存在多少次?
How could one count how many times a substring exists within a string?
我的意思是,如果您有一个字符串 ,一个,两个,三,一,一,二
您怎么能让它出现 3次?
I mean if you have a String "one, two, three, one, one, two"
how could you make it count "one" being present 3 times?
我认为 String.Contains
可以完成这项工作,但是只会检查子字符串是否存在。 String.forall
是用于字符和refrefre的一种选择。
I thought String.Contains
would be able to do the job but that only checks if the substring is present at all. String.forall
is for chars and therefofre niether an option.
所以我在这里真的停了下来。可以让我有资格吗?
So i am really at a complete halt here. Can some enligten me?
推荐答案
您可以使用 Regex.Escape
来将要搜索的字符串转换为正则表达式,然后使用正则表达式函数:
You can use Regex.Escape
to turn the string you're searching for into a regex, then use regex functions:
open System.Text.RegularExpressions
let countMatches wordToMatch (input : string) =
Regex.Matches(input, Regex.Escape wordToMatch).Count
测试:
countMatches "one" "one, two, three, one, one, two"
// Output: 3
这篇关于F#计算子字符串在一个字符串中包含多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!