Question count characters

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
I don't understand why I can not count the selected characters, please help me, thank you.
C#:
using System;
using System.Collections;

namespace ConsoleApp2karater1
{
    class Program
    {
        struct mystruct{
          public char kar;
          public int a;
        }
        static void Main(string[] args)
        {
            int[] a = new int[12];
            int i = 0;
            int j = 0;
            int k = -1;
            int hossz = 0;
            char[] tomb = new char[12];
            int[] tomb2 = new int[12];
            string str1 = "hello world!";
            mystruct[] tmb = new mystruct[12];

            hossz = str1.Length;
            for (i = 0; i < 12; i++)
            {
            for (j = 0; j < 12; j++)
            {
                    if (str1[j] == str1)
                    {
                      
                        a[j] = a[j] + 1;
                        if (a[j] < 2)
                        {
                            //k = k + 1;
                            tomb = str1;
                            tomb2 = 1;
                            k = k + tomb2;
                            //tmb.kar=str1;

                        }
                        else { }
                      

                    }
                  
                }
                Console.Write(a+" i " +i+" k "+k+" "+ tomb + " " + tomb2 + " \n");
              
            }
            k = 0;
            for (i = 0; i < 12; i++)
            {
                tomb2 = tomb2 + 1;
                Console.Write(a + " " + tomb);
                Console.Write(" " + tomb2 + "\n");
            }
                Console.WriteLine("Hello World! ");
        }
    }
}
 
Last edited by a moderator:
In the future, when posting your code, please put them in code tags to make it easier for us to read your code.
 
I think you need to begin with explaining what you are trying to accomplish and why you are doing things that way to reach your goal.

Then next, tell us what problems you are running into with the code that you presented. Are you getting compilation errors, if so what errors are you getting? If you are not getting compilation errors, are you getting runtime errors and if so that are they? If not, tell us what behavior you are seeing and what you were expecting to see.
 
thank you for answer. in a tomb char type variable select all most basic characters from "hello world string" then I try to count them then next step I would count those are repeated but counting, the first step is malfunctioning. I don't get error from compiler but the counting algorithm that normally use for increment does increment in an unexpected way. this if (a[j] < 2) is where I select the characters and thry the counting and get wrong values. please help me, thank you, frank.
also in the future I will format the code, thank you.
 
I forgot to mention the malfunctioning means I get wrong numbers after increment. the number of characters should be 9. than count occurrence. thank you.
 
Does the code even compile? Line 29 doesn't look legal. You can't compare a character against a string.
 
Does the code even compile? Line 29 doesn't look legal. You can't compare a character against a string.
thank you for answer. I am using the string to store a test text, also using the string as array to check it's elements against each other. but something is wrong and as beginner I don't see where and how, please help me. thank you, frank.
 
There are multiple approaches. Let's try covering some of the approaches:

Approach 1: Assume ASCII characters (instead of Unicode that C# uses) and use a hashtable/scoreboard
This is the approach that a C programmer would take. Recall that the most basic glyphs are in the ASCII range of 0 to 127. So you can create an array of integers that has 128 elements:
C#:
int [] count = new int[128];
Then as you iterate over each of the characters in the string, you can bump up the count of characters for that element:
C#:
foreach(char ch in inputString)
{
    int asciiCode = (int) ch;
    count[asciiCode]++;
}
Once you have gone through the input string, then you can show the counts:
C#:
for(int i = 0; i <= 127; i++)
{
    char ch = (char) i;
    Console.WriteLine("The character '{0}' was seen {1} time(s)", ch, count[i]);
}
If you want to show only non-zero counts, add the appropriate logic in the display code to skip zero counts.

Approach 2: Let LINQ do all the hard work
This is the approach that a C# programmer who lives and breathes LINQ everyday would take. The idea here is to breakup the string into a series of characters, and take advantage of LINQ's GroupBy() method to get the unique letters and keep track of the count of each letter.
C#:
var groups = inputString.GroupBy(c => c);
foreach (var g in groups)
    Console.WriteLine("The character '{0}' was seen {1} time(s)", g.Key, g.Count());

Approach 3: Build a list of seen characters and keep track of their counts
This is the approach that Computer Science student would take to account for characters that are beyond the ASCII range, and is knowledgeable about data structures, but not as concerned about CPU runtime complexity. This looks to be what you were attempting to implement in your original code.
First declare a class that holds the character and the count.
C#:
class CharCount
{
    public char Ch { get; set; }
    public int Count { get; set; }
}
and then declare a list of such objects:
C#:
var list = new List<CharCount>();
Then iterate over the characters of the string. In the loop body, we'll make use of the following helper method to see if the character is already in the list. If the helper returns a CharCount object, increment the count in the object, otherwise, create a new CharCount object and insert it into the list:
C#:
CharCount charCount = FindCharCountInList(ch, list);
if (charCount == null)
    list.Add(new CharCount() { Ch = ch, Count = 1 });
else
    charCount.Count++;

The helper method would look something like this:
C#:
CharCount FindCharCountInList(char ch, List<CharCount> list)
{
    foreach (var item in list)
    {
        if (item.Ch == ch)
            return item;
    }
    return null;
}

And then finally it's just a matter of iterating over the list to print out the characters and counts:
C#:
foreach (var charCount in list)
    Console.WriteLine("The character '{0}' was seen {1} time(s)", charCount.Ch, charCount.Count);

Instead of a list, hashtable could be used instead to eliminate the need for the helper method. But if you are going to use a hashtable, might as well go all out for efficiency which leads to the next approach below.

Approach 4: Build a hash table of seen characters and keep track of their counts
So this approach brings us back full circle to what the C programmer would have done, but taking into account that C# strings are composed of Unicode characters, and removing the overhead of needing to declare a separate class. A C# programmer who is more concerned about performance would likely take this approach over the LINQ approach.

So we declare a simple hashtable keyed by the character, and whose value is the count:
C#:
var charCounts = new Dictionary<char, int>();
Iterate over the string characters, and in the loop body we populate or update the hash table elements:
C#:
if (charCounts.ContainsKey(ch))
    charCounts[ch]++;
else
    charCounts[ch] = 1;

And then finally it's just a matter of iterating over the list to print out the characters and counts:
C#:
foreach (var kvp in charCounts)
    Console.WriteLine("The character '{0}' was seen {1} time(s)", kvp.Key, kvp.Value);
 
Back
Top Bottom