简体   繁体   中英

splitting binary string into several two character?

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.

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
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("/");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM