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
Char[] with all allowed delimiters between words. The accepted answer is better if OP doesn't want to count words but occurences(even multiple "Lorem" in a single word like "LoremoLorem"). But that's a different approach and requirement.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.