• Status: Solved
• Priority: Medium
• Security: Public
• Views: 276

# 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.
0
jayrod
• 2
2 Solutions

Commented:
To find the first occurance you might try something like:

int lineNum = 0;
int charPos = -1;

lineNum ++;
while ( line != null ) {
charPos = line.IndexOf( c )
if ( charPos >= 0 ) {
break;
}

lineNum++;
}

At this point if charPos is greater than or equal to 0 you have found the line in lineNum and the position of the character in charPos, otherwise it did not exist in the file....
0

Author Commented:
Hmm.. what about all occurrences?  This a different solution all together?
0

Commented:
To store the occurences i made a class

class Occurence
{
public    int  LineNumber;
public    int  IndexWithinLine;
public Occurence(int lNum, int  iNum)
{
LineNumber = lNum;
IndexWithinLine = iNum;
}
}

Logic for retriving all occurences is :

int lineNum = 0;
ArrayList findings = new ArrayList();
char c =  'c';
string line = null;
while ( (line=tr.ReadLine()) != null )
{
int charPos = 0;
int startIndex = 0;
while(charPos > -1)
{
charPos = line.IndexOf( c,startIndex );
startIndex = charPos + 1;
if ( charPos >= 0 )
{
}
}
lineNum++;
}
0

Commented:
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;

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