Today, I tried to use string methods IndexOf and LastIndexOf to parse a directory entry string that I received across an SSH channel. I guess I should have read the method description closer, but I expected LastIndexOf to find the last space character in a string. The signature I wanted to use is:
public int LastIndexOf(char, int, int);
Reports the index position of the last occurrence of a specified String within this instance. The search starts at a specified character position and examines a specified number of character positions.
It turns out that LastIndex will decrement it's starting index for "count" characters. Here was my incorrect code:
private void method () {
string dirEntry = "-rwxr-xr-x 1 abcde fghij 44458 Feb 22 1987 prt01.txt";
int m, n;
// I thought this would scan from 32 to 44 and find the last space char
m = dirEntry.LastIndexOf(' ', 32, 12);
// it returned 32
// code that does what I wanted:
m = 32;
for(int i=32; i<44; i++)
{
if (ca[i] != ' ')
{
m = i;
break;
}
}
// find first space after the numeric string
n = dirEntry.IndexOf(' ', m+1, 12);
// if m and n are correct, get the file size
string fsize = dirEntry.Substring(m, n-m);
}
Design Note: I must admit that there are alot of "magic numbers" in here. I normally do not write code with magic numbers embedded in it. I prefer to assign class constants, or use INI, XML or database initialization as appropriate.
public int LastIndexOf(char, int, int);
Reports the index position of the last occurrence of a specified String within this instance. The search starts at a specified character position and examines a specified number of character positions.
It turns out that LastIndex will decrement it's starting index for "count" characters. Here was my incorrect code:
private void method () {
string dirEntry = "-rwxr-xr-x 1 abcde fghij 44458 Feb 22 1987 prt01.txt";
int m, n;
// I thought this would scan from 32 to 44 and find the last space char
m = dirEntry.LastIndexOf(' ', 32, 12);
// it returned 32
// code that does what I wanted:
m = 32;
for(int i=32; i<44; i++)
{
if (ca[i] != ' ')
{
m = i;
break;
}
}
// find first space after the numeric string
n = dirEntry.IndexOf(' ', m+1, 12);
// if m and n are correct, get the file size
string fsize = dirEntry.Substring(m, n-m);
}
Design Note: I must admit that there are alot of "magic numbers" in here. I normally do not write code with magic numbers embedded in it. I prefer to assign class constants, or use INI, XML or database initialization as appropriate.
Comments