简体   繁体   中英

Input Text File and Read First Character of Each Line + Count Occurences

I'm trying to count the number of occurrences of the first character per line of a text file.

Example text file:

A

Ab

Ac

Ad

B

Ba

Example output:

A : 4

B : 2

Here's the code that I have so far, the issue is that it doesn't know which characters are the same so there multiple iterations of A, B, C, D, etc...

    string line;    
    char firstChar;        
    private void selectFile()
    {
        openFileDialog1.Title = "Open Text File";
        openFileDialog1.Filter = "Text|*.txt";
        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.FileName = "";
        openFileDialog1.ShowDialog();

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            readFile();
        }
    }

    private void readFile()
    {
        int counter = 0;

        StreamReader readTxt = new StreamReader(openFileDialog1.FileName);
        while ((line = readTxt.ReadLine()) != null)
        {
            charFreq();            
            counter++;
        }
    }

    private void charFreq()
    {
        firstChar = line.ToCharArray()[0];
        var charFreq =
            from c in firstChar.ToString().ToCharArray()
            group c by c into groupFrequencies
            select groupFrequencies;

        foreach (var c in charFreq)
            rTxtOutput.Text += (String.Format("{0} : {1}", c.Key, c.Count())) + "\r\n";
    }

What would be the proper way to do this? Thanks!

You can use LINQ's GroupBy :

var query = File.ReadLines(filePath).Where(line => !String.IsNullOrEmpty(line))
                                    .GroupBy(line => line.First());

In case you want to account for empty lines:

var query = File.ReadLines(filePath).GroupBy(line => line.FirstOrDefault());

So the method should look like:

void PrintCharCount(string filePath)
{
    if (!String.IsNullOrEmpty(filePath))
    {
         var query = File.ReadLines(filePath).Where(line => !String.IsNullOrEmpty(line))
                                             .GroupBy(line => line.First());

         foreach (var g in query)
             Console.WriteLine(g.Key + ": " + g.Count());
    }
}

And you don't need to use StreamReader , File.ReadLines is designed for LINQ as it returns IEnumerable<string> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM