Finding a substring from an array within a string argument
I'm new to Java and doing a course where I need to check to see if a substring from the first column of a 2 dimensional array exists in a String argument. If it does I should replace the substring in the argument string with the string that exists in the second column of the 2 dimensional array, on the same row as the one that was searched.
Here's my code so far...
public static String theClassMethod(String theStringArgument)
int foundAt = 0;
for (int i = 0; i < variableArray.length; i++)
foundAt = theStringArgument.indexOf(variableArray[i]);
if (foundAt > 0)
return replaceEach(theStringArgument, variableArray[i], variableArray[i]);
The code seems to work fine when the substring found in variableArray is the 2nd character in theStringArgument, but when it is the 1st character it doesn't find it, even though it's definately in one of those variableArray positions.
I put the System.out.println(i) into the code so I code watch the iterations, and it just seems to skip over the substring in variableArray as though it doesn't see it.
I assume I'm making some fundamental error, probably in the for loop somewhere but if anyone spots anything I'd be most obliged if you code let me know.
Re: Finding a substring from an array within a string argument
Why do you check to make sure foundAt is greater than 0? I suggest you check out the API for String.indexOf() to see what it returns when the substring is not found and what it returns when the substring is found at the first character.
But why don't you just use a method like replaceAll() instead of all this rigmarole?
PS- Rigmarole is your word of the day.