how to count the number of occurrences of a character in a string

nik
nik
Member
166 Points
6 Posts

I want get the number of occurrences of a particular character in a string. I have following

var str="this is my string";
int characterCount;

characterCount=//some method to get count of character 's'

 

Views: 8695
Total Answered: 1
Total Marked As Answer: 0
Posted On: 02-Sep-2017 06:20

Share:   fb twitter linkedin
Answers
xyan
xyan
Member
76 Points
3 Posts
         

You can use following solutions

var str="this is my string";
int characterCount;
 Solution I) 
Remove the character and compare its length:
characterCount = str.Length - str.Replace("s", "").Length;
 Solution II) 
Split the string into an array using the character as a delimiter:
characterCount = str.Split('s').Length - 1;   
Solution III) 
Use the LINQ 'Count' extension method:
characterCount = str.ToCharArray().Count(c => c == 's');
Posted On: 02-Sep-2017 06:28
 Log In to Chat