将char放入一个java字符串中,每N个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/537174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:57:45  来源:igfitidea点击:

Putting char into a java string for each N characters

javastringchar

提问by Giancarlo

I have a java string, which has a variable length.

我有一个长度可变的java字符串。

I need to put the piece "<br>"into the string, say each 10 characters.

我需要把这件作品"<br>"放入字符串中,比如每 10 个字符。

For example this is my string:

例如,这是我的字符串:

`this is my string which I need to modify...I love stackoverlow:)`

How can I obtain this string?:

我怎样才能获得这个字符串?:

`this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)`

Thanks

谢谢

采纳答案by Jon Skeet

Something like:

就像是:

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

回答by cletus

Try:

尝试:

String s = // long string
s.replaceAll("(.{10})", "<br>");

EDIT:The above works... most of the time. I've been playing around with it and came across a problem: since it constructs a default Pattern internally it halts on newlines. to get around this you have to write it differently.

编辑:以上工作......大部分时间。我一直在玩它并遇到一个问题:因为它在内部构造了一个默认模式,所以它在换行符处停止。要解决这个问题,您必须以不同的方式编写它。

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

and the astute reader will pick up on another problem: you have to escape regex special characters (like "$1") in the replacement text or you'll get unpredictable results.

精明的读者会发现另一个问题:您必须在替换文本中转义正则表达式特殊字符(如“$1”),否则您将得到不可预测的结果。

I also got curious and benchmarked this version against Jon's above. This one is slower by an order of magnitude (1000 replacements on a 60k file took 4.5 seconds with this, 400ms with his). Of the 4.5 seconds, only about 0.7 seconds was actually constructing the Pattern. Most of it was on the matching/replacement so it doesn't even ledn itself to that kind of optimization.

我也很好奇并根据上面的 Jon 对这个版本进行了基准测试。这个要慢一个数量级(60k 文件上的 1000 次替换需要 4.5 秒,他需要 400 毫秒)。在这 4.5 秒中,只有大约 0.7 秒实际构建了模式。大部分是在匹配/替换上,所以它甚至没有导致这种优化。

I normally prefer the less wordy solutions to things. After all, more code = more potential bugs. But in this case I must concede that Jon's version--which is really the naive implementation (I mean that in a good way)--is significantly better.

我通常更喜欢不那么冗长的解决方案。毕竟,更多的代码 = 更多潜在的错误。但在这种情况下,我必须承认 Jon 的版本——这确实是天真的实现(我的意思是在一个很好的方式)——明显更好。

回答by DJClayworth

StringBuilder buf = new StringBuilder();

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

You can get more efficient than that, but I'll leave that as an exercise for the reader.

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

回答by Outlaw Programmer

How about 1 method to split the string every N characters:

每隔 N 个字符拆分字符串的 1 种方法如何:

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

Then another method to insert something after each piece:

然后是另一种在每件作品后插入内容的方法:

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

回答by Outlaw Programmer

To avoid chopping off the words...

为了避免砍掉单词......

Try:

尝试:

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

回答by Dave Jarvis

If you don't mind a dependency on a third-party libraryand don't mind 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);
}

Then:

然后:

split( "This is my string", "<br/>", 5 );  

This doesn't split words at spaces but the question, as stated, doesn't ask for word-wrap.

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

回答by Qarj

I've unit tested this solution for boundary conditions:

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

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

Call with:

致电:

padded("this is my string which I need to modify...I love stackoverflow:)", 10, "<br>");

回答by Mira_Cole

The following method takes three parameters. The first is the text that you want to modify. The second parameter is the text you want to insert every n characters. The third is the interval in which you want to insert the text at.

下面的方法需要三个参数。第一个是您要修改的文本。第二个参数是你想要每 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;
}

You would call to this method like this:

你会像这样调用这个方法:

String splitText = insertEveryNCharacters("this is my string which I need to modify...I love stackoverlow:)", "<br>", 10);

The result is:

结果是:

this is my<br> string wh<br>ich I need<br> to modify<br>...I love <br>stackoverl<br>ow:)

^This is different than your example result because you had a set with 9 characters instead of 10 due to human error ;)

^这与您的示例结果不同,因为由于人为错误,您有一个包含 9 个字符而不是 10 个字符的集合;)

回答by Kashif Ibrahim

You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space:

您可以使用正则表达式 '..' 来匹配每两个字符并将其替换为“$0”以添加空格:

s = s.replaceAll("..", "$0 "); You may also want to trim the result to remove the extra space at the end.

s = s.replaceAll("..", "$0"); 您可能还想修剪结果以删除末尾的额外空间。

Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:

或者,您可以添加否定前瞻断言以避免在字符串末尾添加空格:

s = s.replaceAll("..(?!$)", "$0 ");

s = s.replaceAll("..(?!$)", "$0");

For example:

例如:

String s = "23423412342134"; s = s.replaceAll("....", "$0<br>"); System.out.println(s);

String s = "23423412342134"; s = s.replaceAll("....", "$0<br>"); System.out.println(s);

Output: 2342<br>3412<br>3421<br>34

输出: 2342<br>3412<br>3421<br>34

回答by Vincent Mimoun-Prat

I got here from String Manipulation insert a character every 4th characterand was looking for a solution on Android with Kotlin.

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

Just adding a way to do that with Kotlin (you got to love the simplicity of it)

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

val original = "123498761234"
val dashed = original.chunked(4).joinToString("-") // 1234-9876-1234