StringBuilder replace query
807591Mar 10 2008 — edited Mar 10 2008I am NEW to Java programming.
Attempting to search a password looking for the letter 'l' and replacing with '_'.
e.g. my password = "abcdlefg".
Partial code is as follows:
int startIndex = 0;
int endIndex = 0;
for (int i = 1; i <= password.length(); i++)
{
startIndex = password.indexOf("l", 0);
endIndex = startIndex + 1;
password.replace(startIndex, endIndex, "_");
}
return password;
I expected the startIndex = 4 and endIndex = 5 and then to replace the character starting at index position 4 but ending before index position 5 (i.e. character 'l') to be replaced with "_" but instead I get:
'Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1'.
Can someone please explain why this happens?
Thanks,
Ewizard....