I have a string in .NET like so:
string str = "Lorem ipsum is great. lorem ipsum Lorem...";
I need to get a count of all "Lorem" that matches case as well. So Lorem should appear twice and ignore the lorem.
Thanks.
I have a string in .NET like so:
string str = "Lorem ipsum is great. lorem ipsum Lorem...";
I need to get a count of all "Lorem" that matches case as well. So Lorem should appear twice and ignore the lorem.
Thanks.
You can use Linq.
String searchWhat = "Lorem";
int count = str.Split(new[]{' ','.'}, StringSplitOptions.None)
.Count(w => w == searchWhat);
demo: http://ideone.com/a9XHln
Edit: You have commented that "Lorem Loremo" would count as two, so you want to count all occurences of a given word(case-sentive) even if that word is part of another word. Then you could use String.Contains
:
int count = str.Split(new[]{' ','.'}, StringSplitOptions.None)
.Count(w => w.Contains(searchWhat));
demo: http://ideone.com/fxDGuf
Can be done using Linq
:
string str = "Lorem ipsum is great. lorem ipsum Lorem...";
int loremCount = str.Split(new[]{' ','.',','}, StringSplitOptions.None).Count(s => s.Equals("Lorem"));
If you want to consider "Loremo":
int loremCount = str.Count(s => s.Equals("Lorem"));
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++;
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.
Use the below code:
using System.Text.RegularExpressions;
string text = "Lorem ipsum is great. lorem ipsum Lorem...";
int count = new Regex("Lorem").Matches(text).Count;
Hope it will help you. If not please let me know.