phil
phil

Reputation: 253

How to split each element of a string array and form a new array?

Suppose I have a string array

NumText[]={“00111”, “01110”, “10110”}, 

now I want a new array

BinaryText[]={"0","0","1","1","1"......"1","1","0"}, 

which means I have to split each element of the array NumText[], and combine all the bits I get into a new array. What I can figure out is that I define a string array for each element, like

Binary0=NumText[0].split("");
Binary1=NumText[1].split("");
Binary2=NumText[2].split("");

After that I have to remove the leading zero of each BinaryX, and concatenate them together, which is really a bad idea. Any better ways? I appreciate your help.

Upvotes: 2

Views: 5758

Answers (4)

1218985
1218985

Reputation: 8012

You can try this too...

String[] numText = { "00111", "01110", "10110" };
char[] binaryText = (Arrays.toString(numText).replace("[", "").replace("]", "").replaceAll("[, ]", "")).toCharArray();

Upvotes: 1

tmwanik
tmwanik

Reputation: 1661

String numText[] = { "00111", "01110", "10110" };
StringBuilder sb = new StringBuilder();

for (int i = 0; i < numText.length; i++) {
    numText[i] = numText[i].replaceAll("^[0]*", ""); //Remove leading zeros
    for (int j = 0; j < numText[i].length(); j++) {
        sb.append(numText[i].charAt(j));
    }
}
String[] output = sb.toString().split(""); 

Upvotes: 0

Azad
Azad

Reputation: 5055

I don't know why you removing the Zeros but here is my answer

String [] s = {"01 110"," 10010","01010"};
        ArrayList<String> list= new ArrayList<String>();
        for(int i =0 ; i<s.length;i++){
            s[i]=s[i].replaceAll("[0\\s]", "");
                for(int j = 0 ; j<s[i].length();j++){
                    list.add(Character.toString(s[i].charAt(j)));
                }
        }
        System.out.println(list.toString());

Upvotes: 0

Shadi A
Shadi A

Reputation: 124

use two loops the outer for the whole array and the inner for the string at each index:

StringBuilder temp = new StringBuilder();
for(int i=0; i < numText.length; i++){
   for( int j = 0; j < numText[i].length(); j++){
        temp.append(numText[i].charAt(j));
   }

}

char[] newArray = temp.toCharArray();

Upvotes: 1

Related Questions