java – How Do I Split A String By Line Break?-ThrowExceptions

Exception or error:

I’m a noob to android development and I am trying to split a string multiple times by its multiple line breaks. the string I’m trying to split is pulled from a database query and is constructed like this:

public String getCoin() {
    // TODO Auto-generated method stub
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iQuantity = c.getColumnIndex(KEY_QUANTITY);
    int iOunces = c.getColumnIndex(KEY_OUNCES);
    int iValue = c.getColumnIndex(KEY_VALUE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result + /*c.getString(iRow) + " " +*/ c.getString(iName).substring(0, Math.min(18, c.getString(iName).length())) + "\n";
    }
    c.close();
    return result;

result.getCoin reads as this:

alphabravocharlie

I want to split the string at the line break and place each substring into a String Array. This is my current code:

String[] separated = result.split("\n");
      for (int i = 0; i < separated.length; i++) {
           chartnames.add("$." + separated[i] + " some text" ); 
           }

This gives me an output of:

"$.alpha
bravo
charlie some text"

instead of my desired output of:

"$.alpha some text, $.bravo some text, $.charlie some text"

Any help is greatly appreciated

How to solve:

you can split a string by line break by using the following statement :

   String textStr[] = yourString.split("\\r\\n|\\n|\\r");

###

It’s a little overkill, but you can use the standard I/O classes:

BufferedReader rdr = new BufferedReader(new StringReader(result));
List<String> lines = new ArrayList<String>();
for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
    lines.add(line);
}
rdr.close(); // good form to close streams, but unnecessary for StringReader

// lines now contains all the strings between line breaks of any type

The advantage of this is that BufferedReader.readLine() has all the logic worked out for detecting all sorts of line terminators.

As of Java 8, BufferedReader has a lines() method, so there’s an easier way (thanks, @jaco0646):

List<String> lines = new BufferedReader(new StringReader(result))
                         .lines()
                         .collect(Collectors.toList();

or, if an array is needed instead:

String[] lines = new BufferedReader(new StringReader(result))
                     .lines()
                     .toArray(String[]::new);

###

Using the Apache commons helper class StringUtils.

The platform independent way:

String[] lines = StringUtils.split(string, "\r\n");

The platform dependent way. Maybe some CPU cycles faster. But I wouldn’t expect it to matter.

String[] lines = StringUtils.split(string, System.lineSeparator());

###

If possible I would suggest using the Guava Splitter and Joiner classes in preference to String.split. But even then, it’s important to make sure that you’re properly escaping your regular expressions when declaring them. I’m not certain “\n” won’t be properly interpreted by the regex compiler in Java, but I’m not sure it will be either.

Covering all possible line endings is tricky, since multiple consecutive EOL markers can mess up your matching. I would suggest

String [] separated = result.replaceAll("\\r", "").split("\\n");

###

Matcher m = Pattern.compile("(^.+$)+", Pattern.MULTILINE).matcher(fieldContents);

while (m.find()) {
    System.out.println("whole group " + m.group())
}

###

I propose the following snippet, which is compatiple with PC and Mac endline styles both.

String [] separated = result.replaceAll("\\r", "\\n")
   .replaceAll("\\n{2,}", "\\n")
   .split("\\n");

Leave a Reply

Your email address will not be published. Required fields are marked *