java比较数组

uurv41yg  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(280)

我有几百行代码的字符串数组。我还有另外两个字符串数组,一个带有我想替换的值,另一个带有我想替换的值。我需要遍历原始代码的每一行,检查每一行是否包含需要替换的内容,如果包含,则替换。我想将它替换为一个完全不同的字符串数组,这样原始的字符串仍然保持不变。这就是我所拥有的,但并不完全有效。

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

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

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

    }

}

显然我需要更多的计算变量(特别是因为 originalCode.length !=listOfThingsToReplace.length ),但我不知道在哪里。我需要更多吗?我厌倦了那样做。。。“但是” Exception in thread "main" java.lang.OutOfMemoryError: Java heap space "... 需要帮忙吗?

2ul0zpep

2ul0zpep1#

我想如果我正确理解这个问题的话,这个方法就可以了

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

相关问题