[英]The best way to find how many times a string(or substring) occurs in a large string c#
我不会发布完整的代码,因为我认为对你来说这是一个很有用的练习,但我个人会寻求一个带有起始位置的IndexOf
重载的解决方案。
所以像(注意:故意不正确):
int startingPosition = 0;
int numberOfOccurrences = 0;
do {
startingPosition = fullText.IndexOf("queen", startingPosition);
numberOfOccurrences++;
} while( matchFound );
最短的写作方式。 是使用正则表达式。 它会为你找到匹配。 得到计数。 此外,正则表达式已忽略大小写选项,因此您ToLower
在大字符串上使用ToLower
。 所以你读完文件后
string aliceFile = Path.Combine(Environment.CurrentDirectory, "bestanden\\alice_in_wonderland.txt");
string text = File.ReadAllText(aliceFile);
Regex r = new Regex("queen", RegexOptions.IgnoreCase);
var count = r.Matches(input).Count;
另外,因为输入非常大但模式很简单,所以可以使用RegexOptions.Compiled
来加快速度。
Regex r = new Regex("queen", RegexOptions.IgnoreCase | RegexOptions.Compiled);
var count = r.Matches(input).Count;
您可以编写一个字符串扩展方法来拆分多个字符....
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
....只需使用您要搜索的字符串作为投影仪,然后结果就是数组的长度-1。
string s = "How now brown cow";
string searchS = "ow";
int count = s.split( seacrchS ).Length- 1;
拆分返回的实际数组将是....
["H"," n"," b","n ","c"]
并且扩展方法ALWAAYS将来会再次派上用场。
也可以使用正则表达式:
string s = "Hello my baby, Hello my honey, Hello my ragtime gal";
int count = Regex.Matches(s, "Hello").Count;
或者你可以使用一些linq来做同样的事情
string words = "Hi, Hi, Hello, Hi, Hello"; //"hello1 hello2 hello546 helloasdf";
var countList = words.Split(new[] { " " }, StringSplitOptions.None);
int count = countList.Where(s => s.Contains("Hi")).Count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.