結伙stackoverflow看到一道非常不錯的問題。遂拿來分享之。
題目要求:我有一個非常長的字符串:
String s1="This is my world. This has to be broken."
我要把上面的字符串打亂以固定的長度(比如10)使得輸出為:
This is myworld. This has to be broken.
可是我想讓輸出包括原來的字符的同一時候不不分開一個詞使得輸出例如以下: This is myworld.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 wrapsSystem.out.println( sb );sb.setLength( 0 );}else {// Otherwise add to current linesb.append( ' ' );}
}
// Handle final line
System.out.println( sb );
}
}
此文章頁發表于我博客www.marksaas.com。
假設你有更好的方法,歡迎在以下留言,假設執行正確。我將會把它更新到我的博客上來。
歡迎關注我的微博? ,我的微博會實時更新文章。 ?交流群:?