将字符串分成几个子字符串

时间:2016-11-06 06:50:42

标签: java android

我有一个只包含数字的字符串。字符串本身看起来像“0011112222111000”或“1111111000”。我想知道如何获得一个子串的数组,这些子串只包含一个数字的字符串。 例如,如果我有“00011111122233322211111111110000000”字符串,我希望它在包含string[]的字符串数组(["000","111111","222","333","222","1111111111","0000000"])中。

这就是我试过的

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

但是如果字符串看起来像这样的“111111000”

,则此代码将不起作用

谢谢。

1 个答案:

答案 0 :(得分:2)

  

我有&#34; 00011111122233322211111111110000000&#34;字符串,我喜欢它   在包含的字符串数组(string [])中   [&#34; 000&#34;&#34; 111111&#34;&#34; 222&#34;&#34; 333&#34;&#34; 222&#34;&#34; 1111111111&#34;&#34; 0000000&#34;]

我现在能想到的一种方法( O(n)(可能不是最有效但可以解决你的问题)将遍历字符串数字即(&#34; 00011111122233322211111111110000000&#34;在您的情况下)

如果所考虑的那个位置的char与前一个位置的char不相同,那么将字符串作为一个字符串直到该部分并继续。

(方法)

考虑str =&#34; 00011111122233322211111111110000000&#34;

//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.

<强>码

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

我在这里打印了每个元素作为字符串,如果你需要一个所有那些元素的数组,你可以简单地使用array_list并继续在array_list中添加 one_element 而不是打印。