比较数组
Comparing arrays
我有好几百行代码的字符串数组。我还有另外两个字符串数组,一个是我要替换的值,另一个是我要替换的值。我需要遍历原始代码的每一行并检查每一行是否包含我需要替换的任何内容,如果包含,则替换它。我想把它替换成一个完全不同的字符串数组,这样原来的仍然保持不变。这就是我所拥有的,但它并不完全有效。
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
”......有什么帮助吗?
如果我正确理解问题,我认为这应该可以解决问题
// 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;
}
我有好几百行代码的字符串数组。我还有另外两个字符串数组,一个是我要替换的值,另一个是我要替换的值。我需要遍历原始代码的每一行并检查每一行是否包含我需要替换的任何内容,如果包含,则替换它。我想把它替换成一个完全不同的字符串数组,这样原来的仍然保持不变。这就是我所拥有的,但它并不完全有效。
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
”......有什么帮助吗?
如果我正确理解问题,我认为这应该可以解决问题
// 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;
}