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

问题描述:

我有一个只包含数字的字符串。字符串本身看起来像这样“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”

这个代码将无法正常工作,谢谢。

+5

涉及循环的几行代码会执行。如果您遇到问题,请尝试使用具体问题回来。 Stackoverflow不是一个编码机器! – Henry

+1

@Henry如果存在正则表达式解决方案,这将会很有趣。 –

+1

为什么每个人都会对此表示低估?这是一个完全合法的问题。 –

我有 “00011111122233322211111111110000000” 的字符串,我想要它 在字符串数组(串[]),它包含 [ “000”, “111111”, “222”, “333”,” 222" , “1111111111”, “0000000”]

一个我能想到的,现在的做法(为O(n)(可能不是最有效的,但会解决你的问题)会遍历一串数字即(“00011111122233322211111111110000000”在你的情况下)

如果考虑中该位置的char与先前位置的char不同,则将字符串作为一个字符串并继续。

(方法)

考虑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. 

代码

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并继续添加one_eleme nt in array_list而不是打印。

+0

我已经添加了我的代码,看一看 – Steve

+0

是啊..确保,我正在尝试解决您的问题的代码,并且还会为111110000工作,请给我一些时间! – eRaisedToX

+0

@steve检查我最近的解决方案是否适合您,请随时提供任何其他帮助。即使你的测试用例如str =“111110000”,它也可以工作 – eRaisedToX