Minicl55
Minicl55

Reputation: 987

Read a line from a text file and interpret the character it's on?

I want to read one line of a text file, one character at a time. I figure it'd be something like this:

string[] acct = File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Accts.txt");
for (int i = 0; i >= acct[line].Length; i++)
{

}

But I don't know what goes in the for loop. I want to read each character, and if it's a specific character have it do something else.

Upvotes: 2

Views: 126

Answers (3)

spender
spender

Reputation: 120548

var chars = File.ReadLines(path).SelectMany(x => x);
foreach(char c in chars)
{
    //tada
}

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98868

We don't know what line is on here but since you can use string in foreach lopp you can do;

for (int i = 0; i < acct[line].Length; i++)
{
    foreach(char c in line)
    {
        if(c is specific character)
        {
           //Do something
        }
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504182

It's unclear what you're trying to achieve here, as we don't know what line is, but your for loop condition is the wrong way round to start with. You can use:

for (int i = 0; i < acct[line].Length; i++)
{
    char c = acct[line][i];
    ...
}

But unless you need the index, I'd use:

foreach (char c in acct[line])
{
    ...
}

... and unless you need the index of the line, I'd use foreach for the lines as well.

I probably wouldn't even read them all into memory at the same time unless you really need to:

string directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string path = Path.Combine(directory, "Accts.txt");
foreach (string line in File.ReadLines(path))
{
    foreach (char c in line)
    {
        // ...
    }
}

You may well want to split your code up to make it easier to read, however - write a method to process a single line, so you'd have:

string directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string path = Path.Combine(directory, "Accts.txt");
foreach (string line in File.ReadLines(path))
{
    ProcessLine(line);
}

...

void ProcessLine(string line)
{
    // Do whatever in here
}

This would be much easier to test, as well - as you don't need to read a file to test the handling of a single line.

Upvotes: 4

Related Questions