balexandre
balexandre

Reputation: 75073

How many specified chars are in a string?

taken a string example as 550e8400-e29b-41d4-a716-446655440000 how can one count how many - chars are in such string?

I'm currently using:

int total = "550e8400-e29b-41d4-a716-446655440000".Split('-').Length + 1;

Is there any method that we don't need to add 1... like using the Count maybe?

All other methods such as

Contains IndexOf etc only return the first position and a boolean value, nothing returns how many were found.

what am I missing?

Upvotes: 4

Views: 5837

Answers (7)

Ani
Ani

Reputation: 113402

You can use the LINQ method Enumerable.Count for this purpose (note that a string is an IEnumerable<char>):

int numberOfHyphens = text.Count(c => c == '-');

The argument is a Func<char, bool>, a predicate that specifies when an item is deemed to have 'passed' the filter.

This is (loosely speaking) equivalent to:

int numberOfHyphens = 0;

foreach (char c in text)
{
    if (c == '-') numberOfHyphens++;
}

Upvotes: 18

Guffa
Guffa

Reputation: 700182

The most straight forward method is to simply loop throught the characters, as that is what any algorithm has to do some way or the other:

int total = 0;
foreach (char c in theString) {
  if (c == '-') total++;
}

You can use extension methods to do basically the same:

int total = theString.Count(c => c == '-');

Or:

int total = theString.Aggregate(0, (t,c) => c == '-' ? t + 1 : t)

Then there are interresting (but less efficient) tricks like removing the characters and compare the lengths:

int total = theString.Length - theString.Replace("-", String.Empty).Length;

Or using a regular expression to find all occurances of the character:

int total = Regex.Matches(theString, "-").Count;

Upvotes: 4

Lou Franco
Lou Franco

Reputation: 89152

To find the number of '-' in a string, you are going to need to loop through the string and check each character, so the simplest thing to do is to just write a function that does that. Using Split actually takes more time because it creates arrays for no reason.

Also, it's confusing what you are trying to do, and it even looks like you got it wrong (you need to subtract 1).

Upvotes: 2

codymanix
codymanix

Reputation: 29468

using System.Linq;

..

int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');

Upvotes: 5

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

Try this:

string s = "550e8400-e29b-41d4-a716-446655440000";
int result = s.ToCharArray().Count( c => c == '-');

Upvotes: 1

Lee
Lee

Reputation: 144126

int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-')

Upvotes: 2

LukeH
LukeH

Reputation: 269298

int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');

Upvotes: 4

Related Questions