java - 比较数组

标签 java arrays for-loop

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

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/

相关文章:

arrays - 对 n 元素数组进行排序,使前 k 个元素按升序排列最低(就地算法)

objective-c - 逐个字符循环遍历两个字符串以查找部分字谜

Python SQlite。 LIMIT 变量在循环中不改变值

c - for循环辅助+累加

c# - 需要帮助在 c# 中将数据写入 json

python - 复杂的 numpy 数组乘法

java - 如何使用 JSP、Java Bean 和 Servlet 填充 JSP 表

Java基于两个分隔符对字符串进行排序

java - 为什么这些 JSTL c 是 :tests not stopping the content from being rendered?

java - 回文java程序的数组索引越界异常