14

I wanted to ask how to parse a String and add a Line break (\n) every 100 characters. I know that you can parse The String with Regex, but don't know how to proceed later on. Can somebody help?

1
  • 2
    Post us the code that you have, and we'll help you from there. Commented May 10, 2012 at 8:26

7 Answers 7

84

You could do something like so:

String str = "....";
String parsedStr = str.replaceAll("(.{100})", "$1\n");

This will replace every 100 characters with the same 100 characters and add a new line at the end.

The (.{100}) will capture a group of 100 characters. The $1 in the second will put the content of the group. The \n will be then appended to the 100 characters which have been just matched.

Sign up to request clarification or add additional context in comments.

13 Comments

Weird, never thought about it before... smart indeed.
Very smart solution. +1 I like it.
Nice solution. I should really take some time to understand regex... +1
@TheEliteGentleman: I only figured it out a few months ago, I think I've seen it for the first time on SO.
@T.Grottker: I appreciate your comment.
|
4

Quite simply:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
    if (i > 0 && (i % 100 == 0)) {
        sb.append("\n");
    }

    sb.append(str.charAt(i));
}

str = sb.toString();

1 Comment

Nice one. I did a slightly different approach that doesn't iterate through each index.
1

Could try this perhaps?

String stringToParse = "abcde";

for(int i = 0; i < stringToParse.size(); i = i + 100){
   stringToParse = ((StringBuffer) stringToParse ).insert(i, "\n").toString();
}

6 Comments

That's absolutely wrong, you're just replacing the character with a \n at index i. Besides, Java String can't be indexed.
OP is not trying to modify the original data. This does not work.
I should probably clean the sleep out of my eyes before typing! Editing the answer now.
Can you implicitly convert from String to StringBuffer?
causes much overhead. create a StringBuffer (or better a StringBuilder) and insert the newlines; then convert back to string
|
1

I suggest using StringBuilder. It is efficient and can suit your task exactly.

String originalString = ... ;

// The new length of the string is
int newLength = originalString.length() +(int) Math.ceil ( originalString.length() / 100.0 );

StringBuilder builder = new StringBuilder ( newLength );

I'll refer to each 100 character part of the string as a "chunk" so that its easy to see what's going on.

int chunkStart = 0;

while ( chunkStart < originalString.length() )
{
    // We find the index of the end of the chunk.
    int endOfThisChunk = Math.min ( chunkStart + 100, originalString.length() );

    // and this chunk to builder
    builder.append ( originalString.substring( chunkStart, endOfThisChunk ) );

    // append the new line character
    builder.append ( '\n' );

    // set the next spot for chunkStart
    chunkStart = endOfThisChunk;
}

return builder.toString();

Hope that helps! If you need more explanation please let me know!

Comments

1

i think this is a bit faster than % 100 and repeatedly appending

function(String input) {
    // array represantation of the String
    final char[] inputArray = input.toCharArray();
    // same length + amount of newlines (i.e. length / 100)
    final char[] outputArray = new char[inputArray.length + (inputArray.length/100)];
    int i = 0;
    int o = 0;
    while(i < inputArray.length) {
        // copy every 100th substring
        System.arraycopy(inputArray,i,outputArray,o,100);
        i += 100;
        o += 101;
        outputArray[o] = '\n';
    }
    // copy rest
    if(i < inputArray.length) {
        System.arraycopy(inputArray,i,outputArray,o,inputArray.length-i);
    }
    return(outputArray.toString());
}

though untested

2 Comments

Then your assumption that it's a bit faster than % 100 is unfounded and wrong if it hasn't been tested and compared with other solutions here or you may know of.
well I said I think not it is so. Since op wanted a regex solution and my answer ist just another alternative, I didn't see any need for testing. I just wanted to hint, not to offense
1

There is no need to parse the String via regex, you can just split it.

String s = "your very long String";
String[] splited = new String[s.size() / 100 + 1];
for (int i = 0; i < splited.length(); i++) {
  splited[i] = s.subString(0, 100);
  s = s.subString(100);
}

EDIT

StringBuilder sb = new StringBuilder();
for(int i = 0; i< splited.size(); i++) {
  sb.append(splited[i]);
  sb.append("\n");
}
String stringWithNewLines = sb.toString();

3 Comments

Split and then what? How do you add new lines and join it later?
Did you test your code? I can still see that (the updated code) you have never put a \n nor does it do what the OP asks.
I saved the substrings in an array. It is nearly trival to recombine it and add a newline, but I edit my answer.
0

As you cannot just add more charachters to a regular String in Java. You should use the StringBuffer to do this.

You can loop through the String with a for loop and then so something after every 100th character:

String string = "Some long string ...";
StringBuffer buffer = new StringBuffer();

for(int i = 0; i < string.length(); i++) {
    // Append a \n after every 100th character.
    if((i > 0) && (i % 100) == 0) {
        buffer.append("\n");
    }
    // Just adds the next character to the StringBuffer.
    buffer.append(string.charAt(i));
}

String parsedString = buffer.toString();

3 Comments

It will add a \n at i = 0. See my post.
Why iterate through each i and add a character at a time? Wouldn't it be easier to add one full chunk at a time? (See my post)
Didn't thought of that that quickly. Nice one.