Click here to Skip to main content
14,329,015 members
Rate this:
Please Sign up or sign in to vote.
See more:
hi guys i have a textbox and textBox1.Text is for example: Jack#Alex#Marlo#Jimmy#Bob

now i wanna find out how many [#] is there in the textbox, i know its 4 [#] in that sentence but dont know how to get that count
plzzzzzz help me
Posted
Updated 27-Nov-14 11:32am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

Inspired by the discussion about "unnecessary ToArray() method call", i decide to post this answer to bring more information about the "differences" between methods used in a both solutions (solution 1 and solution 2).

The most important statement is: Both solutions are equivalent and return exactly the same result!
Even if there are few differences (in a scope of code compilation and execution - see below table), it doesn't matter in this case! It might makes a difference only in case when the set of strings comparison is performed.

Solution 1 Solution 2
query syntax method syntax
IL instructions (generated by LinqPad 4):
IL_0001:  ldstr       "Jack#Alex#Marlo#Jimmy#Bob"
IL_0006:  stloc.0     // s
IL_0007:  ldloc.0     // s
IL_0008:  call        System.Linq.Enumerable.ToArray
IL_000D:  ldsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0012:  brtrue.s    IL_0027
IL_0014:  ldnull
IL_0015:  ldftn       b__0
IL_001B:  newobj      System.Func<System.Char,System.Boolean>..ctor
IL_0020:  stsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0025:  br.s        IL_0027
IL_0027:  ldsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_002C:  call        System.Linq.Enumerable.Where
IL_0031:  call        System.Linq.Enumerable.Count
IL_0036:  stloc.1     // SharpCount

b__0:
IL_0000:  ldarg.0
IL_0001:  ldc.i4.s    23
IL_0003:  ceq
IL_0005:  stloc.0     // CS$1$0000
IL_0006:  br.s        IL_0008
IL_0008:  ldloc.0     // CS$1$0000
IL_0009:  ret

IL instructions (generated by LinqPad 4):
IL_0001:  ldstr       "Jack#Alex#Marlo#Jimmy#Bob"
IL_0006:  stloc.0     // theString
IL_0007:  ldloc.0     // theString
IL_0008:  ldsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_000D:  brtrue.s    IL_0022
IL_000F:  ldnull
IL_0010:  ldftn       b__0
IL_0016:  newobj      System.Func<System.Char,System.Boolean>..ctor
IL_001B:  stsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0020:  br.s        IL_0022
IL_0022:  ldsfld      UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0027:  call        System.Linq.Enumerable.Count
IL_002C:  stloc.1     // cntNumberSign

b__0:
IL_0000:  ldarg.0
IL_0001:  ldc.i4.s    23
IL_0003:  ceq
IL_0005:  stloc.0     // CS$1$0000
IL_0006:  br.s        IL_0008
IL_0008:  ldloc.0     // CS$1$0000
IL_0009:  ret

Not uses lambda expressions, but compiler changes the query expression into the equivalent Lambda expression
Uses lambda expressions, so compiler doesn't need to "change" anything.
Time of code execution: 00:00.000
Time of code execution: 00:00.000
Query used in this solution is equivalent to:
int SharpCount = s.Where(c=>c=='#').Select(c=>c).Count();

Query used in this solution does not use Select method.
int cntNumberSign = theString.Count(c => c == '#');



Conclusion:
There is only one (the most important) difference: first solution uses "unnecessary" Select method, but not ToArray()! ;) In both cases ToArray() method is used. In the second one, ToArray method is used indirect, because delegate method must split characters to array to be able to compare each character to '#'.

For further information, please see:
Query Syntax and Method Syntax in LINQ (C#)[^]
Lambda Expressions (C# Programming Guide)[^]

Thank you, anonymous downvoter! You've been my inspiration to take a bit deeper analysis.
   
v2
Comments
Shweta N Mishra 28-Nov-14 3:41am
   
+5 :) i do not understand why people downvote without any explanation/reason.

At least they should have courtesy to comment what they didnt felt right so that we can further improvise our solutions.
Maciej Los 28-Nov-14 3:47am
   
Thank you ;)
Agree!
jaket-cp 28-Nov-14 6:34am
   
Hello Maciej,
I agree, downvoting without comment is harsh.
I like the Linq, but I have put in a solution with 2 unconventional ways of getting the same result.
If you can spare the time, if you could compare them, similarly how you compared the Linq, I would be intested in the result.
Thanks :) also 5ed
Maciej Los 28-Nov-14 6:44am
   
Thank you ;)
BillWoodruff 28-Nov-14 7:47am
   
+5 nice work in analyzing what's happening "down there."
Maciej Los 28-Nov-14 7:49am
   
Thank you, Bill ;)
CPallini 28-Nov-14 9:45am
   
Wow. 5.
Maciej Los 28-Nov-14 10:48am
   
Thank you, Carlo ;)
PIEBALDconsult 28-Nov-14 13:20pm
   
" In the second one, ToArray method is used indirect, because delegate method must split characters to array to be able to compare each character to '#'."

Untrue. You Linq-bois never seem to understand that a String is _already_ an IEnumerable of Char -- it is, in fact, an array of Char.
Maciej Los 28-Nov-14 15:56pm
   
That's what i'm trying to say. Maybe it's unfortunate statement... Remember, English is not native language for hundreds of members (like me).
And please: Do not call me (or anyone else) "Linq-bois". It smells rudely (as per i understand).
PIEBALDconsult 6-Dec-14 18:50pm
   
Oh, sorry, I mean "Linq-fanbois".
PIEBALDconsult 6-Dec-14 18:58pm
   
int SharpCount = s.Where(c=>c=='#').Select(c=>c).Count();
int cntNumberSign = theString.Count(c => c == '#');

In neither of those are you calling ToArray. You're comparing one type of apple with another. Compare them with

int SharpCount = s.ToArray().Where(c=>c=='#').Select(c=>c).Count();
int cntNumberSign = theString.ToArray().Count(c => c == '#');

(Or whatever the syntax is.)
0x01AA 7-Dec-14 11:25am
   
*lol* Maciej, theoretical aspects ok, but sorry for me a little bit "overkill" to count a character.
Kind regards
Bruno
Maciej Los 12-Dec-14 15:03pm
   
Thank you, Bruno ;)
Thomas Daniels 12-Dec-14 13:47pm
   
Nice comparison, +5!
Maciej Los 12-Dec-14 15:03pm
   
Thank you ;)
Rate this:
Please Sign up or sign in to vote.

Solution 4

Here are two unconventional techniques which will get the count of the # charater:
string theString = @"Jack#Alex#Marlo#Jimmy#Bob";

int LengthReplaceCnt = theString.Length - theString.Replace("#","").Length;

int SplitGetUpperBoundCnt = theString.Split('#').GetUpperBound(0);

Not sure how efficient they will be compared to the LINQ solutions.
But I believe the Length, Replace one will fare quite well.
   
Comments
Maciej Los 28-Nov-14 6:43am
   
Nice try, worth a5!
There is nothing to compare to Linq query/method.
jaket-cp 28-Nov-14 6:47am
   
Thanks :)
Yes I like the Linq, but sometimes you just don't know what it is doing under the hood.
Maciej Los 28-Nov-14 6:54am
   
;)
Rate this:
Please Sign up or sign in to vote.

Solution 5

The essense of the task is simply:

int count = 0 ; 
for ( int i = 0 ; i < somestring.Length ; i++ ) 
  if ( somestring [ i ] == soughtchar ) count++ ;


The Linq examples will (in some cases) copy the string, then get an enumerator, then iterate the characters, possibly copy them again, and get a count. The simple for loop will perform only the minimum operations required. And it's recognizable by nearly every developer for the last forty years.

As a general rule, avoid foreach when a for or while loop will suffice.

Furthermore, this code will port to other systems and languages much more easily; Linq won't port.
   
v3
Comments
0x01AA 7-Dec-14 7:51am
   
Quote: "As a general rule, avoid foreach when a for or while loop will suffice."
Why this? Do you have some links to read about this?
Thank you
Bruno

[EDIT]
Just found the links by myself. My 5 because your solution is smart and straight forward and does not blow up everything.
[EDIT]
PIEBALDconsult 7-Dec-14 10:32am
   
Thanks.
Maciej Los 12-Dec-14 17:53pm
   
5ed!
Rate this:
Please Sign up or sign in to vote.

Solution 2

// using Linq

string theString = @"Jack#Alex#Marlo#Jimmy#Bob";

int cntNumberSign = theString.Count(c => c == '#');
   
Comments
Maciej Los 27-Nov-14 17:53pm
   
I like lambda expressions ;)
+5!
BillWoodruff 27-Nov-14 17:56pm
   
Thanks, Maciej !
Maciej Los 27-Nov-14 17:58pm
   
Have you seen my answer?
I'd like to say: different ways to achieve the same ;)
BillWoodruff 27-Nov-14 19:44pm
   
"different ways to achieve the same:" indeed ! I wish I had the "deep inner knowledge" of what the .NET compiler produces (the IL) to be able to immediately visualize what various alternatives do, but I don't, and, at this point in my life, that deep understanding of FrameWork internals is not something I will strive/attempt to achieve. As an American would say, "I have other fish to fry," like a novel in progress, and other passions in life outside of programming.

My hypothesis would be that your example does "more work" than simply using the Count-with-a-Predicate, but, until someone with the expertise reviews the IL, I wouldn't bet on that hypothesis :)
PIEBALDconsult 6-Dec-14 19:01pm
   
" My hypothesis would be that your example does "more work"
"

Yes, it copies the string to another array, needlessly.

PIEBALDconsult 27-Nov-14 18:14pm
   
At least it doesn't use ToArray.
BillWoodruff 27-Nov-14 19:36pm
   
My esteemed colleague, Piebald, if you have a problem with any other person's solution, please take that up directly with them; if you have any suggestions, or criticisms, on how I can improve anything I ever post, I would consider it a gift for you to share them with me. cheers, Bill
Maciej Los 28-Nov-14 3:43am
   
Thank you, Bill. You're completely right. I think that PIEBALDconsult's comment is a voice of His positive opinion about your solution. But, i strongly believe He's wrong. Please, see solution 3. I explained there the differences between both solutions.
PIEBALDconsult 6-Dec-14 18:48pm
   
What irks me most of all about _inexperienced_ users of Linq is their overuse of certain paradigms, e.g. calling something like ToArray<char> on a string simply because they want to iterate the characters -- not realizing that a string is _already_ IEnumerable<char> .
I was pointing out that your Solution demonstrates that ToArray is not required for the task, whereas Solution 1 performs this needless copy operation. It may well not matter to this situation, but other _inexperienced_ developers will see examples such as Solution 1 and think that ToArray (etc.) is required.
I'm sure you know about cargo cult programming.

I come back to this today because of an article that uses
foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
rather than simply
foreach (DataRow dataRow in dataTable.Rows)
Animesh Datta 28-Nov-14 2:21am
   
simple and clear . My 5!
Rate this:
Please Sign up or sign in to vote.

Solution 1

You can use Linq[^]:
string s = @"Jack#Alex#Marlo#Jimmy#Bob";

int SharpCount = (from x in s.ToArray()
    where x == '#'
    select x).Count();

    Console.WriteLine(SharpCount);


Result: 4
   
v2
Comments
BillWoodruff 27-Nov-14 19:36pm
   
Voted #5 to counteract a very unnecessary down-vote.
Maciej Los 28-Nov-14 0:21am
   
Thank you,Bill.
It's quite often practice some persons to downvote someones solution without any explonation.
I'll show you the content of IL for both solutions to be able to discuss about that.
Animesh Datta 28-Nov-14 2:21am
   
My 5!
Maciej Los 28-Nov-14 2:23am
   
Thank you ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100