繁体   English   中英

查找字符串(或子字符串)在大字符串中出现次数的最佳方法c#

[英]The best way to find how many times a string(or substring) occurs in a large string c#

对于学校我必须完成一项任务,我已经提交了,但我写的代码很糟糕,我不喜欢我最终的结果。 所以,我很好奇,在C#中解决以下问题的最佳方法是什么:

'// 4“爱丽丝梦游仙境”中有多少次“女王”出现? 写一些代码来计算它们。

链接到书(pastebin):

我的代码(pastebin): 我的代码(丑陋的)

在写你的答案时,请忽略我的代码。 另外,解释一下你的代码做了什么,以及为什么你认为它是最好的解决方案。 书中“女王”一词出现的次数应为76次。

我不会发布完整的代码,因为我认为对你来说这是一个很有用的练习,但我个人会寻求一个带有起始位置的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM