2015-07-21 31 views
-3

我有一個字符串,並希望有一個數量的字符之後將其分割...Java - 分割後的字符數?

示例代碼:

//This is what I have: 
    String text = "12345678"; 
    List<String> tmpListFirst = new LinkedList<>(); 
    List<String> tmpListSecond = new LinkedList<>(); 
    int splitAfter = 3; //split after the second character (this value is variable) 

    //The result should look like this: 
    tmpListFirst.get(0) //== 678 
    tmpListFirst.get(0) //== 12345 
+1

看那['子串() String]類的'](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))方法 – CubeJockey

+1

你說3之後分裂,但你的輸出表明你想要它分裂後5 – UnknownOctopus

回答

3
String text = "12345678"; 
int splitAfter = 3; 
List<String> tmpListFirst = new LinkedList<>(); 
List<String> tmpListSecond = new LinkedList<>(); 
tmpListFirst.add(text.substring(0, splitAfter)); 
tmpListSecond.add(text.substring(splitAfter)); 

,如果你想存儲在一個值這名單。否則,他們真的可以存儲在字符串只是通過做String s1 = text.substring(0, splitAfter);String s2 = text.substring(splitAfter);

+0

好的答案。 1+並對你以前的答案道歉。原來的海報實際上是想在窗口中顯示圖形,所以很抱歉倒票,它被錯誤地放置。 –

1
String text = "12345678"; 
text = text.substring(0, 1) //will print 1 
text = text.substring(3, text.length()) //will print 45678 
text = text.substring(3) //will also print 45678 

應該是你在尋找什麼。會比使用String.split()方法後n個字符

0

如果我理解正確的要容易得多,你想要做像水木清華

String text = "12345678"; 
System.out.println(text.substring(0, 5)); 
System.out.println(text.substring(5)); 

//-----------output------------- 
12345 
678 
1

試試這個代碼。這會給你到底想要的結果:

String text = "12345678"; 
List<String> tmpListFirst = new LinkedList<>(); 
List<String> tmpListSecond = new LinkedList<>(); 
int splitAfter = 5; //split after the second character (this value is variable) 

//The result should look like this: 
tmpListFirst.add(text.substring(splitAfter));//678 
tmpListSecond.add(text.substring(0, splitAfter)); //== 12345 

System.out.println(tmpListFirst.get(0)); 
System.out.println(tmpListSecond.get(0)); 

如果您不需要使用列表或LinkedList的程序將非常簡單,如: -

String text = "12345678"; 
int splitAfter = 5; //split after the second character (this value is variable) 

System.out.println(text.substring(splitAfter)); //678 
System.out.println(text.substring(0, splitAfter)); //12345