MrAwesome8
MrAwesome8

Reputation: 269

Comparing arrays

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?

Upvotes: 0

Views: 48

Answers (1)

Michael Dowd
Michael Dowd

Reputation: 231

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;
}

Upvotes: 1

Related Questions