Link to home
Start Free TrialLog in
Avatar of jayrod
jayrodFlag for United States of America

asked on

Find position of a character in a file

If I have read a file into memory with a fileReader or one of the other IO methods. How can I find it's location with certainty? i.e. line and position number.
ASKER CERTIFIED SOLUTION
Avatar of NipNFriar_Tuck
NipNFriar_Tuck

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jayrod

ASKER

Hmm.. what about all occurrences?  This a different solution all together?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of NipNFriar_Tuck
NipNFriar_Tuck

No instead of breaking out of the loop you could store the linenum and charpos, maybe something like:

struct CharLinePos {
   int LineNum;
   int CharPos;
}

// I am using 9 as an example but you could use whatever you needed.
CharLinePos[] clps = new CharLinePos[ 9 ];
CharLinePos clp;
int lineNum = 0;
int charPos = -1;
string c = your character....
TextReader tr = your file reader....

string line = tr.ReadLine();
lineNum ++;
while ( line != null ) {
    charPos = line.IndexOf( c )
    if ( charPos >= 0 ) {
        clp = new CharLinePos();
        clp.LineNum = lineNum;
        clp.CharPos = charPos;
        clps[ i++ ] = clp;
    }

    line = tr.ReadLine();
    lineNum++;
}

Now when you are done all occurances are in the clps array.