Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to find particular letter,how many times occur in the given string pl give me solution
Posted
Comments
Sergey Alexandrovich Kryukov 1-Jul-11 2:06am    
My reason for vote of 1: too lazy to look at standard MSDN documentation which comes with every type and type member.
--SA

You can do it the LINQ way:

C#
string s = "How are you doing?";
int count = (from char c in s.ToCharArray()
             where c.Equals('o')
             select c).Count();


This will return 3.

Update : The VB version(thanks to Simon):

VB
Dim s As String = "How are you doing?"
Dim count As Integer = (From c As Char In s.ToCharArray() _
                        Where c.Equals("o"c) _
                        Select c).Count()
 
Share this answer
 
v3
Comments
Simon_Whale 30-Jun-11 5:39am    
There is a sutble difference in VB and that is changing the

c.Equals('o')

to

c.Equals("o"C)

but thanks learnt something new today :) +5
Tarun.K.S 30-Jun-11 5:42am    
Thank you! :)
Aah that's right, didn't notice the VB.NET tag, silly of me!
Sergey Alexandrovich Kryukov 1-Jul-11 2:06am    
My 5.
--SA
Tarun.K.S 1-Jul-11 3:03am    
спасибо SA!
2 methods that I know

1. Loop method with Substring

Dim s As String = "How are you doing?"
Dim Counter As Integer = 0
Dim CharToCount As Char = "o"

For i As Integer = 0 To s.Length - 1
  If s.Substring(i, 1) = CharToCount Then Counter += 1
Next

MsgBox(Counter)


2. LinQ thanks to Tarun K.S

VB
Dim s As String = "How are you doing?"
Dim Count As Integer = (From c As Char In s.ToCharArray Where c.Equals("o"c) Select c).Count
 
Share this answer
 
v3
Comments
Tarun.K.S 30-Jun-11 5:43am    
Exellent! 5+
Sergey Alexandrovich Kryukov 1-Jul-11 2:07am    
Agree, a 5.
--SA
Logically you should loop and count.

But easiest is, you can use String.Split
YourText.Split("c").Length - 1


What it does is, split your text using character.
Text = abcdcbac <br />
Split = ab,d,ba,<blank>

You can subtract 1 to get the count. ;)
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 1-Jul-11 2:08am    
Not really effective, but original non-standard idea. I voted 4 this time.
--SA

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900