+ 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.
4 Réponses
+ 5
using System.Linq;
string s = "success";
int count= s.Where(c=>c=='s').Count();
Console.WriteLine(count);
+ 5
or :
string MyString= "success";
int Count=0;
foreach (char C in MyString)
{
if (C=='s')
Count++;
}
Console.WriteLine(Count);
+ 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.
0
good