Ila
Ila

Reputation: 3538

Split a string within an array list each time a character is encountered

I am trying to break a string down into an array list consisting of lines of text. A line is created either every 90 characters, or when a line break (\r) is encountered.

I am using this to break the string into an array every 90 characters (partionSize in the code):

    private static List<String> getParts(String string, int partitionSize) {
    List<String> parts = new ArrayList<String>();
    int len = string.length();
    for (int i=0; i<len; i+=partitionSize)
    {
        parts.add(string.substring(i, Math.min(len, i + partitionSize)));
    }
    return parts;
    }

How can I modify this so that it checks for line breaks ("\r") and splits each time one is detected, plus splits every 90 characters?

__

UPDATE:

Using Regex solution provided below, like so:

String[] parts = string.split("(?<=\\G.{" + partitionSize + "})|\r|\n"); 

I input a string broken over multiple lines, for example:

 1. 
 2. 
 3. 
 4.
 5. 

When I split it into array[] parts using the regex below, parts.length is 8, and printing each item in parts returns this:

line 0 is 1. 
line 1 is 
line 2 is 2. 
line 3 is 
line 4 is 3.
line 5 is 
line 6 is 4.
line 7 is 
line 8 is 5.

For this case, parts.length should be 5.

Upvotes: 0

Views: 2134

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213391

You can split using the following regex:

String[] arr = str.split("(?<=\\G.{90})|[\r\n]|\r\n");
  • (?<=\\G.{90}) splits on empty string preceded by 90 characters, starting from the previous match. \\G anchor causes the regex to start matching from where the previous match ended. So first it matches 90 characters at the beginning, then it matches the next 90 characters, and so on.
  • [\r\n] splits on either \r or \n.
  • \r\n splits on \r\n, which is line separator on windows.

Demo Code:

String str = "abcdefghi\njkl\rmnopasdf";            
int maxCharacters = 5;

String[] arr = str.split("(?<=\\G.{" + maxCharacters + "})|[\r\n]|\r\n");       
System.out.println(Arrays.toString(arr));

Output:

[abcde, fghi, jkl, mnopa, sdf]

References:

Upvotes: 3

Michael Hoyle
Michael Hoyle

Reputation: 239

I would call string.split("\r") to create an array of string split on a line-break. Then iterate through each one, and if it is over 90 characters long, split it at that point.

Upvotes: 0

Related Questions