对于学校我必须完成一项任务,我已经提交了,但我写的代码很糟糕,我不喜欢我最终的结果。所以,我很好奇,在C#中解决以下问题的最佳方法是什么:
'// 4“爱丽丝梦游仙境”中的“女王”出现了多少次?写一些代码来计算它们。'
链接到该书(pastebin):book
我的代码(pastebin):my code (ugly)
请在写完答案时忽略我的代码。另外,解释一下你的代码做了什么,以及为什么你认为它是最好的解决方案。 书中“女王”一词出现的次数应为76次。
答案 0 :(得分:4)
我不会发布完整的代码,因为我认为将此作为练习尝试是有用的,但我个人会寻求一个解决方案,IndexOf
重载需要一个起始位置。< / p>
所以(注意:故意不正确):
int startingPosition = 0;
int numberOfOccurrences = 0;
do {
startingPosition = fullText.IndexOf("queen", startingPosition);
numberOfOccurrences++;
} while( matchFound );
答案 1 :(得分:2)
最短的写作方式。是使用正则表达式。它会为你找到匹配。得到计数。此外,正则表达式忽略大小写选项,因此您不必在大字符串上使用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;
答案 2 :(得分:1)
您可以编写一个字符串扩展方法来拆分多个字符....
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;
split返回的实际数组是......
["H"," n"," b","n ","c"]
扩展方法ALWAAYS将来会再次派上用场。
答案 3 :(得分:1)
还可以使用正则表达式:
string s = "Hello my baby, Hello my honey, Hello my ragtime gal";
int count = Regex.Matches(s, "Hello").Count;
答案 4 :(得分:0)
或者您可以使用一些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();