+ 2

Is there a way to count number of the same letter in a word or a sentence in C#?

lets say I have a string like "success" And I want to know the number of character 's' that is available in the word, is there a way to do so and be able to print the value which we expect it to be a 3.

18th Feb 2017, 7:19 PM
Tuchy
Tuchy - avatar
4 Réponses
+ 5
using System.Linq; string s = "success"; int count= s.Where(c=>c=='s').Count(); Console.WriteLine(count);
19th Feb 2017, 4:49 AM
HAL8999++;
HAL8999++; - avatar
+ 5
or : string MyString= "success"; int Count=0; foreach (char C in MyString) { if (C=='s') Count++; } Console.WriteLine(Count);
19th Feb 2017, 5:00 AM
HAL8999++;
HAL8999++; - avatar
+ 1
Usually for this you would just loop over the string like an array checking each character against the character you're looking for and if they match increment a variable. However, if you're counting how many of each letter in the alphabet there is, it may be better to use a dictionary key-value pair where the key is the char and the value for that char gets incremented.
18th Feb 2017, 8:49 PM
ChaoticDawg
ChaoticDawg - avatar
0
good
22nd Feb 2017, 7:19 AM
rehena sultana