Java.lang.OutOfMemory error while using substring function inside a loop

时间:2017-07-12 08:19:14

标签: java string

I am trying to remove all the substrings enclosed with in square braces in a given string. I am using a while loop to process the string until there are no square braces [ and ] in the string, and i am using the substring function inside the loop. Here is the code:

public String removeSquareBraceAndEnclosedSubstring(String inputString) {

     //continue until there is atleast one [ and one ]
     while (inputString.indexOf('[') > 0 && inputString.indexOf(']') > 0){

          int lastIndexOfOpenBrace = inputString.lastIndexOf('[');
          int firstIndexOfCloseBrace = inputString.indexOf(']');

          String beforeOpenBrace = inputString.substring(0, lastIndexOfOpenBrace);
          String afterCloseBrace = "";

          if (!inputString.endsWith("]"))
               afterCloseBrace = inputString.substring(firstIndexOfCloseBrace + 1
                                                                 , inputString.length());

          inputString = beforeOpenBrace + afterCloseBrace ;
      }
      return inputString;
}

I am getting an error

java.lang.OutOfMemoryError: Java heap space
java.util.Arrays.copyOfRange(Arrays.java:2694)
java.lang.String.<init>(String.java:203)
java.lang.String.substring(String.java:1913) on calling this method

I do not want to increase the heap size to solve this. I tried making use of functions like intern(), replacing string assignment by calling String constructor. Also i tried processing using a string builder instead of a string. Nothing seems to solve the issue. Is there a better solution or approach to solve this problem?

3 个答案:

答案 0 :(得分:2)

    public class Example{

    public static void main(String[] args) {
        String str1 = "hi [foo [bar] buzz] there [foo]";
        String str2 = "this is a [sample] string [with some substrings enclosed with in square braces] yeah!";
        System.out.println(removeSquareBraceAndEnclosedSubstring(str1));
        System.out.println(removeSquareBraceAndEnclosedSubstring(str2));
    } 

    public static String removeSquareBraceAndEnclosedSubstring(String inputString) {
        while(inputString.contains("[")){
          int openPos = inputString.indexOf('[');
          inputString = inputString.substring(0,openPos)+ inputString.substring(findClosingBrace(inputString.toCharArray(), openPos)+1);
        }
        return inputString.replaceAll("\\s+", " ");
    }

    public static int findClosingBrace(char[] text, int openPos) {
        int closePos = openPos;
        int counter = 1;
        while (counter > 0) {
            char c = text[++closePos];
            if (c == '[') {
                counter++;
            }
            else if (c == ']') {
                counter--;
            }
        }
        return closePos;
    }
}

答案 1 :(得分:0)

当您在彼此旁边有括号时,您的代码会中断:(数字是索引位置)

@Component(
immediate = true,
property = {
"dispatcher=FORWARD",
"dispatcher=REQUEST",
"servlet-context-name=",
"servlet-filter-name=Detail UC Filter",
"url-pattern=/web/guest/" + PropsUtil.get("myPath") + "/*"
}

这是因为您检测到012345678 [hi][bye] 处于索引4;它是什么。您的代码旨在删除在lastIndexOfOpenBracelastIndexOfOpenBrace之间找到的所有内容。 (基本上在索引3和4之间)在这种情况下,没有什么可以删除,并且你陷入无限循环。将此代码放在while循环的开头将删除此错误。

firstIndexOfCloseBrace

可能会有更多错误。我不确定。

答案 2 :(得分:0)

当opentring在打开括号之前有大括号时,你的代码总是会中断。 你可以写一个条件  close bracs index应大于open braces index。