如何计算字符串中字符串的出现次数? [英] How would I count occurrences of a string within a string?
问题描述
我使用以下代码查找字符串中的匹配字符串。
I used the following code to find the matches string within a string.
int x = Regex.Matches("I am good bad good bad bad boy", "bad").Count;
这里输出x = 3。
现在关注我的问题。
Here output x=3.
Now follow my problem.
int x = Regex.Matches("I have a Voucher in AllVoucher", "Voucher").Count;
这里输出x = 2!
此程序还会计算AllVoucher的优惠券。但是我想要计算凭证可以从任何东西开始的地方(如-Voucher,.Vouchar)除了字母。喜欢
Here output x=2!
This program also count Voucher from AllVoucher. But I want to count Voucher where Voucher can start with anything(like -Voucher, .Vouchar) except letter. Like
int x = Regex.Matches("I have a -Voucher in /Voucher", "Voucher").Count;
这里预期输出x = 2;
但是对于预期的以下行是x = 1;
here expected output x=2;
But for the following line expected out is x=1;
int x = Regex.Matches("I have a Voucher in AllVoucher", "Voucher").Count;
这里输出x = 2!
请使用C#.NET给我一个解决方案。如何计算匹配字符串,其中匹配字符串可以从除字母之外的任何内容开始。
Here output x=2!
Please give me a solution using C#.NET. How can I count matches string where matches string can start with anything except letter.
推荐答案
int CountWords(string input, string wordToFind)
{
string pattern = string.Format(@"\b{0}\b", wordToFind);
return Regex.Matches(input, pattern).Count;
}
您可以这样调用此方法:
例如
You can call this method like this:
e.g.
int count = CountWords("I have a -Voucher in /Voucher", "Voucher")
string source = "I am good bad good bad bad boy";
int count = source.Count(f => f == 'bad');
这篇关于如何计算字符串中字符串的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!