Java Method for Replacing String in a Text

  • Context: Java 
  • Thread starter Thread starter JaysFan31
  • Start date Start date
  • Tags Tags
    Method
Click For Summary

Discussion Overview

The discussion revolves around a Java programming task where participants are trying to implement a method that replaces occurrences of a substring within a string. The focus is on debugging and refining the code to handle various cases, particularly when the replacement string is longer than the substring being replaced.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant describes their initial implementation of a string replacement method and expresses confusion over "index out of range" errors when trying to replace substrings.
  • A revised code snippet is provided by the same participant, which still encounters issues when the replacement string is longer than the substring being replaced, despite appearing to work correctly at certain steps.
  • Another participant points out that changing the original string affects the length variable, suggesting that the length should be recalculated after modifications.
  • A further suggestion is made regarding adjusting the loop index when a match is found, to avoid unintended behavior in subsequent iterations.
  • One participant proposes using Java's built-in string replacement method, `replaceAll`, as a more efficient solution, emphasizing the importance of using standard library functions.

Areas of Agreement / Disagreement

Participants express differing views on the best approach to implement the string replacement functionality. While some suggest refining the original method, others advocate for using built-in Java methods. There is no consensus on the optimal solution.

Contextual Notes

Participants note limitations related to variable scope and string length recalculations, which may affect the correctness of the implementation. The discussion also highlights the potential for errors when modifying strings within loops.

Who May Find This Useful

This discussion may be useful for beginner Java programmers seeking to understand string manipulation, debugging techniques, and the use of standard library functions in programming.

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
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".
 
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.
 
Thank you so much. It was as simple as changing "lengthOriginal" and just making it "original.length()."

Again I really appreciate it.
 
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.
 
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.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
Replies
4
Views
3K
Replies
2
Views
2K
  • · Replies 28 ·
Replies
28
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K