Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
3.67/5 (5 votes)
See more:
Hi!

I am a beginner in c#.
My question is, how can I count the number of characters in a string?
Example: in some text i need to find certain letter (how many times is that letter is showing up) using foreach loop.

Thx
Posted
Updated 31-May-23 22:44pm
v3

Why must you use a foreach loop? Since you're a beginner, here are some much more interesting solutions to look at!

C#
string str = "abcdaab";

//Solution 1 - remove the character, and compare its length.
int result1 = str.Length - str.Replace("a", "").Length;

//Solution 2 - split the string into an array using the character as a delimiter
int result2 = str.Split('a').Length - 1;

//Solution 3 - use the LINQ 'Count' extension method
int result3 = str.ToCharArray().Count(c => c == 'a');
 
Share this answer
 
v2
Comments
Kim Togo 6-Apr-11 9:59am    
My 5 for solution 3. Linq is a powerfull tool.
Sergey Alexandrovich Kryukov 6-Apr-11 14:59pm    
This one is good, especially link. Instead of "" you should better use string.Empty.
Hard-coded (immediate) constants are bad, but for the codelet maybe acceptable.
5 anyway.
--SA
C#
int count = 0;
char charToCount = 'i';
foreach (char c in string123)
{
    if( c == charToCount )
    {
        count++;
    }
}


The above code will help you find the no. of instance of a particular character, here 'i', in the string, string123.
 
Share this answer
 
v3
Comments
JOAT-MON 6-Apr-11 5:54am    
wrapped code block
try this

C#
string abc="1234567777";
           int  k = abc.Length;


C#
string abc = "adkjddaadtyy";
            int Count=0;
            foreach (char c in abc)
            {
                if (c == 'd')
                {
                    Count++;
                }
            }
            int k = Count;
 
Share this answer
 
v2
If you're already using a foreach loop then you don't need, a priori, such a info.
e.g.:
C#
String s = "foo abc";
int count = 0;
foreach (char c in s)
{
  count++;
}
 
Share this answer
 
v2
Comments
JOAT-MON 6-Apr-11 5:37am    
I think OP is looking for frequency of a specific letter in the foreach, not just full count.
Syed Nasser Ahmed 19-Oct-19 10:03am    
static void CountLetters()
{
string str = "ThisIsAWord";
char[] strChars = str.ToArray();
int[] cntr = new int[str.Length];
int i = 0;
string retString = string.Empty;

foreach (char c in str)
{
cntr[i] = countChars(c, str);
i++;
}

i = 0;

foreach (int j in cntr)
{
retString += strChars[i] + " Occurs " + j + " times" + "\n";
i++;
}

Console.WriteLine(retString);
Console.Read();
}

static int countChars(char c, string str)
{
int cntr = 0;

foreach (char cNew in str)
{
if (c == cNew) cntr++;
}

return cntr;
}

This may not be the best solution, suggestions are most welcome...
Dictionary<string, int> characterCountList = new Dictionary<string, int>();

string word = "BaNAna";
word = word.ToLower();

bool check = false;
foreach(var c in word)
{
    var count = 0;
    foreach(var character2 in word)
    {
        if (!characterCountList.ContainsKey(c.ToString()))
        {
            check = true;
            if (character2 == c)
            {
                count++;
            }
        }
        else check = false;
    }
    if(check) characterCountList.Add(c.ToString(), count);
}

foreach(var data in characterCountList) Console.WriteLine(data.ToString());
C#

 
Share this answer
 
Comments
CHill60 18-Jul-22 8:19am    
A code dump without commentary does not make a good solution. As the original question is over 11 years old, you are likely to find this solution downvoted, probably several times. You should add some words indicating that this code will give you a count of how many times each unique letter appears in the word or phrase.
I would also advise against adding solutions to such old questions unless you really highlight the new technique that you are bringing to the thread
Richard Deeming 19-Jul-22 4:35am    
Aside from the perfectly valid points in the other comment, this code is appalling.

Your nested loops are O(N²), when a simple O(N) solution exists. Your inner nested loop short-circuits inside the loop, when it could just as easily short-circuit outside the loop. You're allocating new strings that aren't required, just because you started with the wrong key type for your dictionary. You're normalizing the string to lower-case, ignoring the Turkish İ problem[^].

With the tiniest bit of thought, you can clean up your code:
Dictionary<char, int> characterCount = new Dictionary<char, int>();
foreach (char c in word)
{
    char normalizedChar = char.ToUpper(c);
    characterCount.TryGetValue(normalizedChar, out int count);
    // If the key does not already exist, count will be initialized to 0 here.
    characterCount[normalizedChar] = count + 1;
}

foreach (KeyValuePair<char, int> pair in characterCount)
{
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}

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