我有一个java字符串,它有一个可变长度。
我需要将片段"<br>"
放入字符串中,比方说每10个字符。
例如,这是我的字符串:
`this is my string which I need to modify...I love stackoverlow:)`
我怎样才能获得这个字符串?:
`this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)`
谢谢
就像是:
public static String insertPeriodically(
String text, String insert, int period)
{
StringBuilder builder = new StringBuilder(
text.length() + insert.length() * (text.length()/period)+1);
int index = 0;
String prefix = "";
while (index < text.length())
{
// Don't put the insert in the very first iteration.
// This is easier than appending it *after* each substring
builder.append(prefix);
prefix = insert;
builder.append(text.substring(index,
Math.min(index + period, text.length())));
index += period;
}
return builder.toString();
}
尝试:
String s = // long string
s.replaceAll("(.{10})", "$1<br>");
编辑:上述作品......大部分时间。我一直在玩它并遇到一个问题:因为它在内部构造了一个默认模式,它在新行上停止。要解决这个问题,你必须以不同的方式写出来。
public static String insert(String text, String insert, int period) {
Pattern p = Pattern.compile("(.{" + period + "})", Pattern.DOTALL);
Matcher m = p.matcher(text);
return m.replaceAll("$1" + insert);
}
精明的读者会发现另一个问题:你必须在替换文本中逃避正则表达式特殊字符(如“$ 1”),否则你将得到不可预知的结果。
我也很好奇并对这个版本进行了基准测试,反对Jon的上述内容。这个速度慢了一个数量级(60k文件上的1000个替换用了4.5秒,用了400ms)。在4.5秒中,实际构建模式只有大约0.7秒。大多数是在匹配/替换上,所以它甚至没有进行这种优化。
我通常更喜欢不那么罗嗦的解决方案。毕竟,更多代码=更多潜在的错误。但在这种情况下,我必须承认Jon的版本 - 这真的是天真的实现(我的意思是以一种好的方式) - 明显更好。
您可以使用正则表达式“..”匹配每两个字符,并将其替换为“$ 0”以添加空格:
s = s.replaceAll(“..”,“$ 0”);您可能还希望修剪结果以删除末尾的额外空间。
或者,您可以添加负前瞻断言以避免在字符串末尾添加空格:
s = s.replaceAll(“..(?!$)”,“$ 0”);
例如:
String s = "23423412342134";
s = s.replaceAll("....", "$0<br>");
System.out.println(s);
输出:2342<br>3412<br>3421<br>34
为了避免切断单词......
尝试:
int wrapLength = 10;
String wrapString = new String();
String remainString = "The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog";
while(remainString.length()>wrapLength){
int lastIndex = remainString.lastIndexOf(" ", wrapLength);
wrapString = wrapString.concat(remainString.substring(0, lastIndex));
wrapString = wrapString.concat("\n");
remainString = remainString.substring(lastIndex+1, remainString.length());
}
System.out.println(wrapString);
如果你不介意依赖third-party library而不介意regexes:
import com.google.common.base.Joiner;
/**
* Splits a string into N pieces separated by a delimiter.
*
* @param text The text to split.
* @param delim The string to inject every N pieces.
* @param period The number of pieces (N) to split the text.
* @return The string split into pieces delimited by delim.
*/
public static String split( final String text, final String delim, final int period ) {
final String[] split = text.split("(?<=\\G.{"+period+"})");
return Joiner.on(delim).join(split);
}
然后:
split( "This is my string", "<br/>", 5 );
这不会在空格处分割单词,但如上所述,问题并不是要求自动换行。
StringBuilder buf = new StringBuilder();
for (int i = 0; i < myString.length(); i += 10) {
buf.append(myString.substring(i, i + 10);
buf.append("\n");
}
你可以比这更有效率,但我会把它作为读者的练习。
我已针对边界条件对此解决方案进行了单元测试:
public String padded(String original, int interval, String separator) {
String formatted = "";
for(int i = 0; i < original.length(); i++) {
if (i % interval == 0 && i > 0) {
formatted += separator;
}
formatted += original.substring(i, i+1);
}
return formatted;
}
致电:
padded("this is my string which I need to modify...I love stackoverflow:)", 10, "<br>");
如何将每N个字符拆分一个字符串的方法:
public static String[] split(String source, int n)
{
List<String> results = new ArrayList<String>();
int start = 0;
int end = 10;
while(end < source.length)
{
results.add(source.substring(start, end);
start = end;
end += 10;
}
return results.toArray(new String[results.size()]);
}
然后在每件之后插入一些东西的另一种方法:
public static String insertAfterN(String source, int n, String toInsert)
{
StringBuilder result = new StringBuilder();
for(String piece : split(source, n))
{
result.append(piece);
if(piece.length == n)
result.append(toInsert);
}
return result.toString();
}
以下方法需要三个参数。第一个是您要修改的文本。第二个参数是您要插入每n个字符的文本。第三个是您要在其中插入文本的时间间隔。
private String insertEveryNCharacters(String originalText, String textToInsert, int breakInterval) {
String withBreaks = "";
int textLength = originalText.length(); //initialize this here or in the start of the for in order to evaluate this once, not every loop
for (int i = breakInterval , current = 0; i <= textLength || current < textLength; current = i, i += breakInterval ) {
if(current != 0) { //do not insert the text on the first loop
withBreaks += textToInsert;
}
if(i <= textLength) { //double check that text is at least long enough to go to index i without out of bounds exception
withBreaks += originalText.substring(current, i);
} else { //text left is not longer than the break interval, so go simply from current to end.
withBreaks += originalText.substring(current); //current to end (if text is not perfectly divisible by interval, it will still get included)
}
}
return withBreaks;
}
您可以像这样调用此方法:
String splitText = insertEveryNCharacters("this is my string which I need to modify...I love stackoverlow:)", "<br>", 10);
结果是:
this is my<br> string wh<br>ich I need<br> to modify<br>...I love <br>stackoverl<br>ow:)
^这与您的示例结果不同,因为由于人为错误,您有一个包含9个字符而不是10个字符的集合;)