我有几百行代码的字符串数组。我还有另外两个字符串数组,一个包含我想要替换的值,另一个包含我想要替换的值。我需要检查原始代码的每一行,并检查每一行是否包含我需要替换的内容,如果包含,请替换它。我想将其替换为完全不同的字符串数组,以便原始的仍然保持不变。这就是我所拥有的,但它并不完全有效。
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
),但我不知道在哪里。我需要更多的 for 循环吗?我厌倦了这样做......但是“线程“main”java.lang.OutOfMemoryError中的异常:Java堆空间
”......请帮忙吗?
最佳答案
如果我正确理解了问题,我认为这应该可以解决问题
// 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;
}
关于java - 比较数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956766/