user3266638
user3266638

Reputation: 449

Getting count of first character in a text file?

I have a large text file that looks like this where there is one row with an A at the beginning and one C at the end and an x number of B's in between:

A

B

B

B

C

What's the best way to get a number count for the number of times A, B, or C appear? All of these rows have more data but this is what I'm trying to achieve.

Do I have to read in the whole file or is reading it one line at a time the best?

Upvotes: 3

Views: 245

Answers (3)

Cabbage Champion
Cabbage Champion

Reputation: 1213

The below snippet of code is a easy implementation:

 int iBCount = File.ReadAllLines(filePath).Count -2;
 int iACount = 1; // We already knew this
 int iCCount = 1; // We already knew this

Also, if you know size in bytes of each line (they must be the same for each line) and you are concerned with the performance then you can simply calculate the number of "B" lines as follows

 // There will be no problem with typecast if each lines is the same length in bytes
 int iBLines = (int)(new System.IO.FileInfo(pathToFile).Length / FIXED_LINE_SIZE_IN_BYTES); 

Upvotes: 1

trotunno
trotunno

Reputation: 1

string [] lines = File.ReadAllLines(filePath)

int A_count = 0, B_count = 0, C_count = 0;
foreach (string line in lines)
{
    switch(line[0])
    {
        case 'A':
            A_count++;
            break;
        case 'B':
            B_count++;
            break;
        case 'C':
            C_count++;
    }
}

Upvotes: 0

slig_3
slig_3

Reputation: 125

I think something like that would work

foreach (var grouping in File.ReadAllLines("<file-path-here>").GroupBy(x => x[0]))
{
    Console.WriteLine($"char: {grouping.Key}, count: {grouping.Count()}");
}

Upvotes: 2

Related Questions