Click here to Skip to main content
15,910,980 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In Particular word, count a particular Character.
For Example : Count 'O' word in Download.
Result Count : 2
Posted
Updated 12-Aug-11 1:29am
v2

using Linq:
C#
myString.Count(ch => ch == 'C');
 
Share this answer
 
Comments
#realJSOP 12-Aug-11 7:37am    
5 - that's the best way as long as you're using an appropriate version of .Net
Depends on what you like:

C#
// given the following, and assuming you don't care about case-sensitivity:
string myString = "Download";
char myChar = 'o';
int count = 0;

// if case-sensitivity matters, comment these two lines
myChar = myChar.ToLower();
myString = myString.ToLower()

// do this:
foreach (char c in myString)
{
    count += (c = myChar) ? 1 : 0;
}

// or this:
count = myString.Count(ch => ch == myChar);

// or this:
int count = (from c in myString
             where c == myChar
             select c).Count();
 
Share this answer
 
Comments
thatraja 12-Aug-11 7:57am    
5!
Member 11995255 24-Mar-16 22:05pm    
wrong!
it's count += (c == myChar) ? 1 : 0; instead of count += (c = myChar) ? 1 : 0;
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


Is one method using LinQ
 
Share this answer
 
Write a function n pass char to search and string

VB
Public Function CountChar(ByVal str As String, ByVal Ch1 As Char) As Integer
  Dim iCnt As Integer = 0
  For Each c As Char In str
     If c = Ch1 Then iCnt += 1
 Next
CountChar = iCnt
End Function
 
Share this answer
 

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