Java Method for Replacing String in a Text

  • Thread starter JaysFan31
  • Start date
  • Tags
    Method
In summary, the conversation is about a person seeking help with creating a method in Java that replaces occurrences of a second string with a third string in a given string. They have shared their code and asked for help with fixing "index out of range" errors. Another person has suggested using the Java docs and standard library for a more efficient solution.
  • #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.

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;
}
 
Technology news on Phys.org
  • #2
This is my revised code:

*Note* I'm just including the last section (the else statement similar to the code in my first post):

Code:
else
  {
	for (int i = 0; i <= (lengthOriginal - lengthFind); i++)
	{
	  String partBefore;
	  String partAfter;
	  mutation = original.substring(i, i + lengthFind);
	  if (mutation.equals(find))
	  {
		partBefore = original.substring(0, i);
		partAfter = original.substring(i + lengthFind);
		original = partBefore.concat(replacement);
		original = original.concat(partAfter);
		System.out.println(original);
	  }
	  finalString = original;
	}
	finalString = original;
  }

It works perfectly if LengthFind <= LengthReplacement. I just can't get it to work when lengthReplacement is larger than the LengthFind. It does everything correctly. It compiles and I even included the System.out.println(original); to see what the string looks like at that step (it's correct there.) However, it prints like ten lines of "index out of range" errors still. Obviously, it's working. I just can't get it to work without these errors. Can anyone help me?

Again, I want to input something like ("She sells seashells", "he", "h") and output "Sh sells seashlls".
 
  • #3
If you change the length of the string "original", then your variable "lengthOriginal" is no longer the length of the string.

Also, when you find a match, you might want to think about adjusting "i" as well. For example if you replaced ab with aa, this might happen:

abbbxx becomes aabbxx
then
aabbxx becomes aaabxx
then
aaabxx becomes aaaaxx

which might not be what you wanted.
 
  • #4
Thank you so much. It was as simple as changing "lengthOriginal" and just making it "original.length()."

Again I really appreciate it.
 
  • #5
You should use Java docs and the standard library. The Java Way:

Code:
/**
	 * Replaces each occurrence of the find string in original string with
	 * replacement string
	 * 
	 * @param original
	 * @param find
	 * @param replacement
	 * @return replaced string.
	 */
	public static String replaceString(String original, String find,
			String replacement) {

		return original.replaceAll(find, replacement);
	}

If nothing else try to use JavaDocs for comments.
 
  • #6
haki said:
You should use Java docs and the standard library. The Java Way:

Code:
/**
	 * Replaces each occurrence of the find string in original string with
	 * replacement string
	 * 
	 * @param original
	 * @param find
	 * @param replacement
	 * @return replaced string.
	 */
	public static String replaceString(String original, String find,
			String replacement) {

		return original.replaceAll(find, replacement);
	}

If nothing else try to use JavaDocs for comments.

Somehow I get the feeling he won't get very many marks for that solution.
 

1. How do I use the Java method for replacing a string in a text?

The Java method for replacing a string in a text is the replace() method. It takes two parameters: the old string to be replaced and the new string to replace it with. For example, if you have a string variable named myString with the value "Hello, world!", and you want to replace the word "world" with "universe", you can use the following code: myString.replace("world", "universe");

2. Can the Java replace method replace multiple occurrences of a string?

Yes, the Java replace() method can replace multiple occurrences of a string. By default, it will replace all occurrences of the old string. However, you can specify the maximum number of replacements by using the replaceFirst() or replaceAll() methods instead. These methods take a regular expression as the first argument, which allows for more complex replacements.

3. What happens if the old string is not found in the text?

If the old string is not found in the text, the replace() method will simply return the original text without making any changes. This means that the method will not throw an error if the old string is not found.

4. Can the Java replace method replace case-sensitive strings?

Yes, the replace() method in Java is case-sensitive, meaning that it will only replace the exact string that is specified. For example, if you have a string "Hello, world!" and you try to replace "hello" with "hi", the method will not make any changes since the case does not match.

5. Is there a way to replace a string without modifying the original text?

Yes, you can use the replaceAll() method to replace a string without modifying the original text. This method creates a new string with the replacements, leaving the original text unchanged. However, it is important to note that strings in Java are immutable, meaning they cannot be changed. The replaceAll() method does not actually modify the original string, but rather creates a new string object with the desired replacements.

Similar threads

  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
1
Views
3K
  • Programming and Computer Science
Replies
4
Views
5K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
Back
Top