在Java中以字符方式包装string之后的string

我有这个代码:

String s = "A very long string containing " + "many many words and characters. " + "Newlines will be entered at spaces."; StringBuilder sb = new StringBuilder(s); int i = 0; while ((i = sb.indexOf(" ", i + 20)) != -1) { sb.replace(i, i + 1, "\n"); } System.out.println(sb.toString()); 

代码的输出是:

 A very long string containing many many words and characters. Newlines will be entered at spaces. 

上面的代码是在每30个字符的下一个空格之后包装string,但是我需要在每个30个字符的前一个空格之后包装string,就像第一行那样:

A very long string

而第二行将是

 containing many 

请给一些适当的解决办法。

你可以使用Apache-common的 WordUtils.wrap() 。

使用lastIndexOf而不是indexOf ,例如

 StringBuilder sb = new StringBuilder(s); int i = 0; while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) { sb.replace(i, i + 1, "\n"); } System.out.println(sb.toString()); 

这将产生以下输出:

 A very long string containing many many words and characters. Newlines will be entered at spaces. 

您可以尝试以下方法:

 public static String wrapString(String s, String deliminator, int length) { String result = ""; int lastdelimPos = 0; for (String token : s.split(" ", -1)) { if (result.length() - lastdelimPos + token.length() > length) { result = result + deliminator + token; lastdelimPos = result.length() + 1; } else { result += (result.isEmpty() ? "" : " ") + token; } } return result; } 

调用为wrapString(“asd xyz afz”,“\ n”,5)

“\ n”制作一个wordwrap。

 String s = "A very long string containing \n" + "many many words and characters. \n" + "Newlines will be entered at spaces."; 

这将解决你的问题

 public static void main(String args[]) { String s1="This is my world. This has to be broken."; StringBuffer buffer=new StringBuffer(); int length=s1.length(); int thrshld=5; //this valueis threshold , which you can use int a=length/thrshld; if (a<=1) { System.out.println(s1); }else{ String split[]=s1.split(" "); for (int j = 0; j < split.length; j++) { buffer.append(split[j]+" "); if (buffer.length()>=thrshld) { int lastindex=buffer.lastIndexOf(" "); if (lastindex<buffer.length()) { buffer.subSequence(lastindex, buffer.length()-1); System.out.println(buffer.toString()); buffer=null; buffer=new StringBuffer(); } } } } } 

这可以成为一种方法