结伙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。
假设你有更好的方法,欢迎在以下留言,假设执行正确。我将会把它更新到我的博客上来。
欢迎关注我的微博 ,我的微博会实时更新文章。 交流群: