0

I have String Array of a good couple hundred lines of code. I have two other String Arrays, one with values I want to replace, and the other with the value I want it to replace to. I need to go through each line of the original code and check each line if it contains anything that I need to replace, and if it does, replace it. I want to replace it to a totally different String Array, so that the original is still left unchanged. This is what I have, but it's not exactly working.

for(int i=0; i<originalCode.length; i++) {

    if( originalCode[i].contains("| "+listOfThingsToReplace[i]) ) {

        newCode[i]=originalCode[i].replaceAll(("| "+listOfThingsToReplace[i]), ("| "+listOfReplacingThings[i]));

    }

}

Obviously I need more counting variables somewhere (especially because originalCode.length !=listOfThingsToReplace.length), but I can't figure out where. Would I need more for loops? I tired doing that... but "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"... Any help please?

1
  • Use replace() which replaces all occurrences of plain-text, not replaceAll() which replaces all occurrences of a regex match. Commented Jan 15, 2015 at 6:11

1 Answer 1

1

I think this should do the trick if I'm understanding the problem correctly

// New Code Array
String[] newCode = new String[originalCode.length];

for (int i=0; i<originalCode.length; i++) {
	// New Code Line
	String newCodeLine = originalCode[i];

	// Iterate through all words that need to be replaced
	for (int j=0; j<listOfThingsToReplace.length; j++) {
		
		// String to replace
		String strToReplace = listOfThingsToReplace[j];
		
		// String to replace with
		String strToReplaceWith = (j >= listOfReplacingThings.length) ? "" : listOfReplacingStrings[j];
		
		// If there is a string to replace with
		if (strToReplaceWith != "") {
			
			// then replace all instances of that string
			newCodeLine = newCodeLine.replaceAll(strToReplace, strToReplaceWith);
		}		
	}
	
	// Assign the new code line to our new code array
	newCode[i] = newCodeLine;
}

Sign up to request clarification or add additional context in comments.

2 Comments

Use !strToReplaceWith.equals("") instead of !=. Plus that part doesn't even make sense; how could j be greater than the length when you have the check in your for loop.
You're right about the .equals, I always forget about that. I put the check with j to handle the situation where listofReplacingThings.length is less than listOfThingsToReplace.length, but may or may not be necessary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.