在java中按长度拆分String

时间:2012-11-09 17:13:47

标签: java android

  

可能重复:
  Split string to equal length substrings in Java

我有一个String []数据结构,就像这样

0.1953601.3675211.3675214.1025640.5860811.36752110.3540903.711844-5.2747252.539683

我想把它拆成像这样的数组

  0.195360
  1.367521
  1.367521
  4.102564
  0.586081
  1.367521
 10.354090
  3.711844
 -5.274725
  2.539683

所以在小数点后,这些值有6位有效数字

我尝试使用来自this question的正则表达式解决方案,但它似乎无法正常工作。

即便如此

System.out.println(Arrays.toString(
  "Thequickbrownfoxjumps".split("(?<=\\G.{4})")
));

为我提供了[Theq, uickbrownfoxjumps]而不是[Theq, uick, brow, nfox, jump, s]的输出结果。

2 个答案:

答案 0 :(得分:4)

断言

  

每个值的大小为8,但如果值为负则为9

问题中的

是假的,因为如果我在这里手动拆分条目就是结果:

0.195360
1.367521
1.367521
4.102564
0.586081
1.367521
10.35409
03.71184   <<< As you can see, it's not that you want
4-5.2747   <<< It's not a number
252.5396
83         <<< Bang! too short

我认为真正的断言是“点后面的数字是6”,在这种情况下,拆分成为:

  0.195360
  1.367521
  1.367521
  4.102564
  0.586081
  1.367521
 10.354090
  3.711844
 -5.274725
  2.539683

代码在这里:

static String[] split( String in ) {
   List< String > list = new LinkedList< String >();
   int dot = 0;
   for( int i = 0; dot > -1 && i < in.length(); i = dot + 7 ) {
      dot = in.indexOf( '.', i );
      if( dot > -1 ) {
         int last = Math.min( dot + 7, in.length());
         list.add( in.substring( i, last ));
      }
   }
   return list.toArray( new String[list.size()]);
}

答案 1 :(得分:0)

正则表达式不是很好的应用恕我直言:

 while not end-of-string
   if next-char is "-"
      take next 9 chars
   else
      take next 8 chars
相关问题