Steve - 1 year ago 100
Java Question

# Divide string into several substrings

I have a strings that contain only digits. String itself would look like this "0011112222111000" or "1111111000". I'd like to know how can I get an array of substrings which will consist of strings with only one digit.
For example, if I have "00011111122233322211111111110000000" string, I 'd like it to be in string array(

`string[]`
) which contains
`["000","111111","222","333","222","1111111111","0000000"]`
.

This is what I've tried

``````for (int i = (innerHierarchy.length()-1); i >= 1; i--) {
Log.e("Point_1", "innerHierarchy " + innerHierarchy.charAt(i));
c = Character.toChars(48 + max);
Log.e("Point_1", "c " + c[0]);
if (innerHierarchy.charAt(i) < c[0] && innerHierarchy.charAt(i - 1) == c[0]) {
Log.e("Point_1", "Start " + string.charAt(i));
o = i;
} else if (innerHierarchy.charAt(i) == c[0] && innerHierarchy.charAt(i - 1) < c[0]) {
Log.e("Point_1", "End " + string.charAt(i));
o1 = i;
string[j] = string.substring(o1,o);
j=j+1;
}
}
``````

But this code won't work if string looks like this "111111000"

Thank you.

I have "00011111122233322211111111110000000" string, I 'd like it to be in string array(string[]) which contains ["000","111111","222","333","222","1111111111","0000000"]

One approach I can think of right now (O(n)) (might not be the most efficient but would solve your problem) would be traversing the string of numbers i.e. ("00011111122233322211111111110000000" in your case )

and if char at that position under consideration is not same as char at previous position then making string till that part as one string and continuing.

(approach)

considering str= "00011111122233322211111111110000000"

``````//starting from position 1 (ie from 2nd char which is '0')

//which is same as prev character ( i.e 1st char which is '0')
// continue in traversal
// now char at pos 2 which is again '0'
// keep traversing
// but then char at position 3 is 1
// so stop here and
//make substring till here-1 as one string
//so "000" came as one string
//continue in same manner.
``````

code

``````   import java.util.*;

public class A {
public static void main(String []args){
String str = "00011111122233322211111111110000000";
str+='-';  //appended '-' to get last 0000000 as well into answer
//otherwise it misses last string which i guess was your problem
String one_element ="";
int start=0;

for(int i=1;i<str.length();i++){
if(str.charAt(i)== str.charAt(i-1) )
{

}
else{
one_element = str.substring(start,i);
start = i;
System.out.println(one_element);//add one_element into ArrayList if required.
}
}
}
}
``````

I have printed each element here as string , if you need an array of all those you can simply use an array_list and keep adding one_element in array_list instead of printing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download