剛在stackoverflow看到一道很不錯的問題,遂拿來分享之。
題目要求:我有一個很長的字符串:
String s1="This is my world. This has to be broken."
我要把上面的字符串打亂以固定的長度(例如10)使得輸出爲:
This is my
world. Thi
s has to b
e broken.
但是我想讓輸出包含原來的字符的同時不不分開一個詞使得輸出如下:
This is my
world.
This has
to be
broken.
下面是一個完整的程序。
/**
author :marksaas
blog: http://www.marksaas.com
交流羣:199326422
time:2014/5/8
*/
public class StringTest{
public static void main(String[] args){
int limit=10;
String s="This is my world. This has to be broken.";
String[] words=s.split(" ");
StringBuilder sb=new StringBuilder();
for(String word:words){
sb.append( word );
if( sb.length()> limit ) {
// Next word wraps
System.out.println( sb );
sb.setLength( 0 );
}
else {
// Otherwise add to current line
sb.append( ' ' );
}
}
// Handle final line
System.out.println( sb );
}
}
此文章頁發表於我博客www.marksaas.com。
如果你有更好的方法,歡迎在下面留言,如果運行正確,我將會把它更新到我的博客上來。
歡迎關注我的微博 ,我的微博會實時更新文章。 交流羣: