1

I have a binary string like "100010". I want split it into several two character like -> "10", "00", "10".

How can i do it? Unfortunately I have no idea about it.

String str = "100010";  
int counter=0,end=1;  

for (int h = 0; h < str.length(); h++) {
     String ss = str.substring(counter, end);
     System.out.print(ss);
     counter = counter + 2;
     end = end + 2;
}

Please help mee.

andr
  • 15,970
  • 10
  • 45
  • 59
Sheila D
  • 27
  • 1
  • 5
  • http://stackoverflow.com/questions/3760152/split-string-to-equal-length-substrings-in-java might help – Swapnil Jan 12 '13 at 15:29
  • What do you see when you step through your program in you debugger? Did you want to have space between the numbers? – Peter Lawrey Jan 12 '13 at 15:32

2 Answers2

3

As you want to split the every 2 characters, you need to keep the difference between counter and end to be equal to 2. The variable h is redundant and in fact will cause a StringIndexOutOfBoundsException:

String str = "100010"; 
int counter = 0;
int end = 2;

while (end <= str.length()) {

   String ss = str.substring(counter, end);
   System.out.println(ss);

   counter += 2;
   end += 2;
}

Alternatively, you could do a regex split for every 2 characters. This uses regex look-behind combined with \G, the zero-width assertion that matches the position where the previous match ended:

for (String s: "100010".split("(?<=\\G..)")) { System.out.println(s);  }

Both versions produce:

10
00
10
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0
private String[] StringSpliter(String OriginalString) {
    String newString = "";
    for (String s: OriginalString.split("(?<=\\G..)")) { 
        if(s.length()<3)
            newString += s +"/";
        else
            newString += StringSpliter(s) ;
    }
    return newString.split("/");
}
newMaziar
  • 41
  • 1