0

我在.NET中有一个字符串,如下所示:

string str = "Lorem ipsum is great. lorem ipsum Lorem...";

我还需要计算所有匹配大小写的“Lorem”。所以 Lorem 应该出现两次并忽略 lorem。

谢谢。

4

6 回答 6

8
string str = "Lorem ipsum is great. lorem ipsum Lorem...";
string word = "Lorem";
Console.WriteLine(Regex.Matches(str,word).Count);
于 2012-10-22T21:09:08.923 回答
6

您可以使用 Linq。

String searchWhat = "Lorem";
int count = str.Split(new[]{' ','.'}, StringSplitOptions.None)
               .Count(w => w == searchWhat);

演示:http: //ideone.com/a9XHln

编辑:您评论说“Lorem Loremo”将计为两个,因此您想要计算给定单词(区分大小写)的所有出现,即使该单词是另一个单词的一部分。然后你可以使用String.Contains

int count = str.Split(new[]{' ','.'}, StringSplitOptions.None)
               .Count(w => w.Contains(searchWhat));

演示:http: //ideone.com/fxDGuf

于 2012-10-22T21:06:44.903 回答
0

Here's my 2 cents. It will find all instances of "Lorem" case sensative, but it will return a count for things that have "Lorem" in it, like "Loremo" or "thismightnotLorembewhatyouwant".

The question was a bit vague so this answer is a quick solution that conforms to what you requested.

string test = "Lorem ipsum is great. lorem ipsum Lorem...";

int pos = -1;
int count = 0;
while ((pos = test.IndexOf("Lorem", pos+1)) != -1)
    count++;
于 2012-10-22T21:14:45.303 回答
0

If you want this to be able to perform other operations, you can dump the entire string into a List and then you could run Linq queries off off that list.

var phrase = "Lorem ipsum...";
var wordList = phrase.Split(' ').ToList();
var loremCount = wordList.Where(x => x.ToLower() == "lorem").Count();

This way wordList is reusable.

于 2012-10-22T21:16:43.867 回答
0

使用以下代码:

using System.Text.RegularExpressions;

string text = "Lorem ipsum is great. lorem ipsum Lorem...";
int count = new Regex("Lorem").Matches(text).Count;

希望它会帮助你。如果没有,请告诉我。

于 2012-10-22T21:31:00.677 回答
0

可以使用Linq

string str = "Lorem ipsum is great. lorem ipsum Lorem...";
int loremCount = str.Split(new[]{' ','.',','}, StringSplitOptions.None).Count(s => s.Equals("Lorem"));

如果你想考虑“Loremo”:

int loremCount = str.Count(s => s.Equals("Lorem"));
于 2012-10-22T21:06:37.693 回答