1

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;
  }
1
  • Would substring help? Commented Mar 29, 2019 at 19:56

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.