How many characters are given in a string?

took an example of a string how 550e8400-e29b-41d4-a716-446655440000, how can I count the number of characters - in such a string?

I am currently using:

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

Is there any method that we do not need to add 1 ... for example, using Count, maybe?

All other methods, such as

Contains IndexOfetc. return only the first position and value boolean, returns nothing how much .

What am I missing?

+3
source share
7 answers

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

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

- Func<char, bool>, , , "" .

( ) :

int numberOfHyphens = 0;

foreach (char c in text)
{
    if (c == '-') numberOfHyphens++;
}
+16
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-');
+4
using System.Linq;

..

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

, :

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

, :

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

:

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

( ) , :

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

:

int total = Regex.Matches(theString, "-").Count;
+4
int total = "550e8400-e29b-41d4-a716-446655440000".Count(c => c == '-')
+2

To find the number β€œ-” in a string, you will need to skip the string and check each character, so the simplest thing is to simply write a function that does this. Using Split actually takes longer because it creates arrays for no reason.

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

+2
source

Try the following:

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

Source: https://habr.com/ru/post/1770098/


All Articles