2009-02-11 97 views
16

我有一个java字符串,它具有可变长度。将char放入每个N个字符的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:)` 

感谢

回答

20

喜欢的东西:

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(); 
} 
+0

太棒了!如果我不想把
放在文字中,怎么样?for例如避免这样的事情:stackover
流和直接放
在单词的结尾? – Giancarlo 2009-02-11 15:09:30

+1

然后这是一个非常困难的问题。正则表达式*可能是最好的方式,但是您需要先确定需求。 – 2009-02-11 15:14:34

32

尝试:

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

我得到: 无效的转义序列(有效的有\ B \吨\ n \˚F\ r \” \” \ \) for“(。{1,10} \ s +” – 2009-02-11 15:04:00

+0

修正了它,它应该是\\ s,但我错误地认为你想打破字界限,你不这样做,以上应该工作而且要容易得多 – cletus 2009-02-11 15:05:56

1
StringBuilder buf = new StringBuilder(); 

for (int i = 0; i < myString.length(); i += 10) { 
    buf.append(myString.substring(i, i + 10); 
    buf.append("\n"); 
} 

你可以得到比这更有效的,但我会离开,作为一个练习留给读者。

0

怎么样1的方法来分割字符串每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(); 
} 
3

为了避免斩去的话...

尝试:

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); 
3

如果你不介意在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); 

这没有按”在空间分割词语,但如上所述,问题并不要求单词换行。

0

我已经单元测试该溶液为边界条件:

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>"); 
0

下面的方法采用三个参数。第一个是你想要修改的文本。第二个参数是要插入每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,因为人为错误;)

0

您可以使用正则表达式'..'来匹配每两个字符并将其替换为“$ 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

相关问题