31

我有一个 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:)`

谢谢

4

12 回答 12

52

尝试:

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 的版本——实际上是天真的实现(我的意思是一种很好的方式)——明显更好。

于 2009-02-11T15:01:03.660 回答
38

就像是:

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();
}
于 2009-02-11T15:01:37.480 回答
16

我从String Manipulation 来到这里,每 4 个字符插入一个字符,并正在使用 Kotlin 在 Android 上寻找解决方案。

只需添加一种使用 Kotlin 的方法(您必须喜欢它的简单性)

val original = "123498761234"
val dashed = original.chunked(4).joinToString("-") // 1234-9876-1234
于 2020-04-23T08:49:01.670 回答
15

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

于 2018-03-01T21:18:20.070 回答
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); 
于 2009-05-11T03:28:07.597 回答
3

如果您不介意对第三方库的依赖并且不介意正则表达式

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

这不会在空格处拆分单词,但如前所述,问题不要求自动换行。

于 2016-06-22T20:22:35.713 回答
1
StringBuilder buf = new StringBuilder();

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

您可以获得比这更高的效率,但我将把它作为练习留给读者。

于 2009-02-11T15:04:03.293 回答
1

我已经针对边界条件对该解决方案进行了单元测试:

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>");
于 2017-12-07T23:22:44.603 回答
0

一种方法如何每隔 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();
}
于 2009-02-11T15:04:06.993 回答
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 个字符的集合;)

于 2018-02-23T15:31:03.437 回答
0

Kotlin 正则表达式版本:

fun main(args: Array<String>) {    
    var original = "this is my string which I need to modify...I love stackoverlow:)"
    println(original)
    val regex = Regex("(.{10})")
    original = regex.replace(original, "$1<br>")
    println(original)
}

科特林游乐场

于 2020-05-20T16:37:20.677 回答
0
String s = // long string
String newString = String.join("<br>", s.split("(?<=\\G.{10})"));

<br>如果slength 是 的倍数,则不添加final 10

感谢@cletus和这个灵感的答案

于 2021-04-14T11:04:08.007 回答