C# 获取多个包含的和

C# 获取多个包含的和,c#,string,count,sum,contains,C#,String,Count,Sum,Contains,我有一个字符串,例如“这是一个例子”,在这句话中是另一个词——“一个小测试”。我想知道有多少次是“一个小测试”的句子。有办法吗?谢谢 string tmp = "This a little test is a little test an example. a little test"; int sum = ...... (the count of "a little test") 你可以这样做: int sum = Regex.Matches(tmp, "a little test").Co

我有一个字符串,例如“这是一个例子”,在这句话中是另一个词——“一个小测试”。我想知道有多少次是“一个小测试”的句子。有办法吗?谢谢

string tmp = "This a little test is a little test an example. a little test";
int sum = ...... (the count of "a little test")

你可以这样做:

int sum = Regex.Matches(tmp, "a little test").Count;

如果“搜索项”可能包含可在正则表达式中使用的字符,则可能需要使用
Regex.Escape

int sum = Regex.Matches(tmp, Regex.Escape(@"my search term with $pecia| $ymb\0Ls")).Count;

你可以这样做:

int sum = Regex.Matches(tmp, "a little test").Count;

如果“搜索项”可能包含可在正则表达式中使用的字符,则可能需要使用
Regex.Escape

int sum = Regex.Matches(tmp, Regex.Escape(@"my search term with $pecia| $ymb\0Ls")).Count;

@cookiesoft的可能副本尽管所引用问题的标题可能暗示其他,但实际问题(和接受的答案)是针对字符串中单个字符的出现,而不是OP要求的内容。请参见,其中一致意见是“不,他们不应该”!@cookiesoft的可能副本尽管所引用问题的标题可能暗示其他,但实际问题(和接受的答案)是针对字符串中单个字符的出现,而不是OP要求的内容。请参见,其中一致意见是“不,他们不应该”!太棒了+1.另外(供进一步阅读):非常棒+1.另外(供进一步阅读):