jayrod
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER