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?

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228

7 Answers7

82

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.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • Weird, never thought about it before... smart indeed. – Buhake Sindi May 10 '12 at 08:32
  • 5
    Very smart solution. +1 I like it. – tgr May 10 '12 at 08:32
  • 2
    Nice 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
  • @T.Grottker: I appreciate your comment. – npinti May 10 '12 at 08:42
  • @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
  • Perfect, thats what I wanted to reproduce. – daniel souza May 14 '16 at 00:51
  • dang, big brain guy – ObscurusLux Feb 15 '23 at 14:00
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();
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
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();
}
David K
  • 692
  • 10
  • 23
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();
tgr
  • 3,557
  • 4
  • 33
  • 63
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!

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

Hachi
  • 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
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();
Wouter Konecny
  • 3,260
  • 3
  • 19
  • 26