English 中文(简体)
字符串中特定字符串的数量
原标题:Quantity of specific strings inside a string

I m working in .net c# and I have a string text = "Whatever text FFF you can FFF imagine"; What i need is to get the quantity of times the "FFF" appears in the string text. How can i acomplished that? Thank you.

最佳回答

您可以使用正则表达式来匹配任何您想要的内容。

string s = "Whatever text FFF you can FFF imagine";

Console.WriteLine(Regex.Matches(s, Regex.Escape("FFF")).Count);
问题回答

这里有两种方法。请注意,正则表达式应该使用单词边界的元字符,以避免错误的匹配到其他单词中的出现。到目前为止发布的解决方案没有这样做,这将错误地计算“fooFFFbar”中的“FFF”作为匹配。

string text = "Whatever text FFF you can FFF imagine fooFFFbar";

// use word boundary to avoid counting occurrences in the middle of a word
string wordToMatch = "FFF";
string pattern = @"" + Regex.Escape(wordToMatch) + @"";
int regexCount = Regex.Matches(text, pattern).Count;
Console.WriteLine(regexCount);

// split approach
int count = text.Split(   ).Count(word => word == "FFF");
Console.WriteLine(count);
Regex.Matches(text, "FFF").Count;

请使用 System.Text.RegularExpressions.Regex 来完成此操作:

string p = "Whatever text FFF you can FFF imagine";
var regex = new System.Text.RegularExpressions.Regex("FFF");
var instances = r.Matches(p).Count;
// instances will now equal 2,

这里除了经常表述外,还有一种选择:

string s = "Whatever text FFF you can FFF imagine FFF";
//Split be the number of non-FFF entries so we need to subtract one
int count = s.Split(new string[] { "FFF" }, StringSplitOptions.None).Count() - 1;

如果需要的话,您可以轻松地调整它以使用几个不同的字符串。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签