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?

- 87,898
- 29
- 167
- 228
-
2Post us the code that you have, and we'll help you from there. – Jon May 10 '12 at 08:26
7 Answers
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.

- 51,780
- 5
- 72
- 96
-
-
5
-
2Nice solution. I should really take some time to understand regex... +1 – Wouter Konecny May 10 '12 at 08:39
-
@TheEliteGentleman: I only figured it out a few months ago, I think I've seen it for the first time on SO. – npinti May 10 '12 at 08:41
-
-
@WouterKonecny: Regular expressions are very powerful. The same can be said to the headaches they have the potential of causing ;). I would recommend one would learn regular expressions, no need to become an expert, but some basic knowledge will get you a long way, especially if you need to do some string validation. What you need to keep in mind is that regular expressions **must not** be used for parsing ;). – npinti May 10 '12 at 08:44
-
but one more.. in default, symbol 'all-eating-dot' `.` doesn't it `\n`. – gaussblurinc May 10 '12 at 09:00
-
@loldop: I do not understand your question. Also, with regards to my previous point (which I can't seem to edit), regular expressions must not be used to parse irregular languages, such as HTML. – npinti May 10 '12 at 09:03
-
trying to parse this string `...\n\n...` with this regexp `/.+/`. symbol `.` doesn't eat `\n`(newline-symbol) in default-state. – gaussblurinc May 10 '12 at 09:08
-
@loldop: Yes what you are saying should be correct, but the `\n` is a character, albeit special. The OP wants to throw in a break line every 100 characters. You might be able to get round this by using the `Pattern` class and not using the `DOTMATCHESALL` (or something similar) flag. – npinti May 10 '12 at 09:13
-
Yes, very good solution - and for once a regexp which is not hard to read! :) – Prof. Falken May 15 '12 at 08:03
-
-
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();

- 87,898
- 29
- 167
- 228
-
Nice one. I did a slightly different approach that doesn't iterate through each index. – Kaushik Shankar May 10 '12 at 08:39
Could try this perhaps?
String stringToParse = "abcde";
for(int i = 0; i < stringToParse.size(); i = i + 100){
stringToParse = ((StringBuffer) stringToParse ).insert(i, "\n").toString();
}

- 692
- 10
- 23
-
3That's absolutely wrong, you're just replacing the character with a `\n` at index `i`. Besides, Java String can't be indexed. – Buhake Sindi May 10 '12 at 08:27
-
OP is not trying to modify the original data. This does not work. – Kaushik Shankar May 10 '12 at 08:28
-
I should probably clean the sleep out of my eyes before typing! Editing the answer now. – David K May 10 '12 at 08:30
-
-
causes much overhead. create a StringBuffer (or better a StringBuilder) and insert the newlines; then convert back to string – Hachi May 10 '12 at 08:46
-
Cheers for the constructive criticism, I've been afraid to even write an answer on here after some bad early experiences and down voting. I'll be sure to read up about StringBuilder. – David K May 10 '12 at 09:02
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,557
- 4
- 33
- 63
-
-
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. – Buhake Sindi May 10 '12 at 08:34
-
I saved the substrings in an array. It is nearly trival to recombine it and add a newline, but I edit my answer. – tgr May 10 '12 at 08:51
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!

- 5,491
- 4
- 30
- 36
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

- 3,237
- 1
- 21
- 29
-
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. – Buhake Sindi May 10 '12 at 11:17
-
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 – Hachi May 11 '12 at 18:04
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,260
- 3
- 19
- 26
-
-
1Why 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) – Kaushik Shankar May 14 '12 at 19:37
-