Jeffrey Baker
Jeffrey Baker

Reputation: 19

Divide a string into an ArrayList

I'm trying to divide a String into arrays. The overall program is supposed to turn binary into a string but the problem I'm having is dividing the string into arrays. I feel stupid because this seems like a simple thing to do. the binary comes like this "0100100001001001" instead of "01001000" "01001001".

public static ArrayList<String> divStr(String str,int div){

    String addable = "";
    ArrayList<String> ret = new ArrayList<String>();
    for(int i = 0; i < str.length();i++){
      addable += str.charAt(i);
      if(i % div == 0 && i != 0){
        ret.add(addable);
        addable = "";
      }
    }
    return ret;
  }

Upvotes: 1

Views: 105

Answers (3)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You can use split with regex like so :

String[] ret = str.split("(?<=\\G.{" + div +"})");

If you want to return a List :

public static List<String> divStr(String str, int div) {
    return Arrays.asList(str.split("(?<=\\G.{" + div +"})"));
}

If you call the method for example :

System.out.println(divStr("0100100001001001", 8));
>> [01001000, 01001001]

If you mean by div the number of parts you can change your code to be :

public static List<String> divStr(String str, int div) {
    int length = str.length() / div;
    return Arrays.asList(str.split("(?<=\\G.{" + length +"})"));
}

then :

System.out.println(divStr("0100100001001001", 2));
>> [01001000, 01001001]

Upvotes: 1

forpas
forpas

Reputation: 164224

There are 2 problems with your code.
(1) The condition i % div == 0 && i != 0 is wrong because say div = 8, it will add the first 9 chars to the list when i = 8.
(2) If the length of the string str is not a multiple of div there will be chars left out from the list.
So change to this:

public static ArrayList<String> divStr(String str,int div){
    String addable = "";
    ArrayList<String> ret = new ArrayList<String>();
    for(int i = 0; i < str.length();i++){
        addable += str.charAt(i);
        if((i + 1) % div == 0){
            ret.add(addable);
            addable = "";
        }
    }
    if (!addable.isEmpty()) ret.add(addable);
    return ret;
}

Upvotes: 1

Syed Mehtab Hassan
Syed Mehtab Hassan

Reputation: 1337

The problem is with i % div which only came once in your code because it starts from 0 and goes to
str.length = 15 it should be replaced by (i+1) % div

public static ArrayList<String> divStr(String str,int div){

    String addable = "";
    ArrayList<String> ret = new ArrayList<String>();
    for(int i = 0; i < str.length();i++){
      addable += str.charAt(i);
      if((i+1) % div == 0 && i != 0){
        ret.add(addable);
        addable = "";
      }
    }
    return ret;
  }

Upvotes: 0

Related Questions