- #1
JaysFan31
Hi. I just need some help tweaking a program I'm working on for a class. I just started taking Java a few weeks ago, so I need to use elementary language.
Basically, I have to create a method that does what it says in the comment (replace each occurrence of the second string in the first string with the third string).
The first two loops work (if and else if) obviously work fine. I just need help with the third one (when the lengthFind < lengthOriginal). The code makes sense to me and it compiles. However, I get all kinds of "index out of range" problems. I have no idea how to fix these and because of that I can't check my code anyways.
With something like ("She sells seashells by the sea shore", "sh", "shm"), I should return "She sells seashmells by the sea shmore".
Any help, advice, or tiny tweaks to the code would be appreciated. I'm pretty much out of ideas at this point.
Basically, I have to create a method that does what it says in the comment (replace each occurrence of the second string in the first string with the third string).
The first two loops work (if and else if) obviously work fine. I just need help with the third one (when the lengthFind < lengthOriginal). The code makes sense to me and it compiles. However, I get all kinds of "index out of range" problems. I have no idea how to fix these and because of that I can't check my code anyways.
With something like ("She sells seashells by the sea shore", "sh", "shm"), I should return "She sells seashmells by the sea shmore".
Any help, advice, or tiny tweaks to the code would be appreciated. I'm pretty much out of ideas at this point.
Code:
// (c) method called replaceString
// method looks for occurrences of second string in first string
// method replaces each occurrence of second string in first string with third string
public static String replaceString(String original, String find, String replacement)
{
int lengthOriginal = original.length();
int lengthFind = find.length();
int lengthReplacement = replacement.length();
String finalString = "";
String mutation = "";
if (lengthFind > lengthOriginal)
{
finalString = original;
}
else if (lengthFind == lengthOriginal)
{
if (find.equals(original))
{
finalString = replacement;
}
else
{
finalString = original;
}
}
else
{
for (int i = 0; i <= lengthOriginal; i++)
{
String partBefore;
String partAfter;
char characterOriginal = original.charAt(i);
char characterFind = find.charAt(0);
mutation = original.substring(i, i + lengthFind);
if (mutation.equals(find))
{
partBefore = original.substring(0, i);
partAfter = original.substring(i + lengthFind);
finalString = partBefore + replacement + partAfter;
}
}
finalString = original;
}
return finalString;
}