Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between String.Count and String.Length?

Tags:

string

c#

count

I'm using them alternately, is there any difference between them?

like image 302
Patryk Avatar asked Mar 27 '12 05:03

Patryk


People also ask

What is meant by string length?

The length or size of a string means the total number of characters present in it.

What is difference between length and count in C#?

Length is a property returning the number of elements in an Array . Count() is a LINQ extension that does the same on an IEnumerable . Optionally, it can take a predicate as parameter, and will return the number of elements that satisfy it.

How do you calculate the length of a string?

As you know, the best way to find the length of a string is by using the strlen() function.

What is the value of string length?

The string length method returns the number of characters written in the String. This method returns the length of any string which is equal to the number of 16-bit Unicode characters in the string.


2 Answers

On the surface they would seem functionally identical, but the main difference is:

  • Length is a property that is defined of strings and is the usual way to find the length of a string

  • .Count() is implemented as an extension method. That is, what string.Count() really does is call Enumerable.Count(this IEnumerable<char>), a System.Linq extension method, given that string is really a sequence of chars.

Performance concerns of LINQ enumerable methods notwithstanding, use Length instead, as it's built right into strings.

like image 95
BoltClock Avatar answered Sep 28 '22 03:09

BoltClock


String implements the IEnumerable, so it has a method Count while Length is a property in the String class.

like image 29
abhinav Avatar answered Sep 28 '22 04:09

abhinav