26

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

B. Money
  • 931
  • 2
  • 19
  • 56

6 Answers6

60

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

   String textStr[] = yourString.split("\\r\\n|\\n|\\r");
Community
  • 1
  • 1
RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
19

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);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • This is even simpler in Java 8, which added a [lines() method](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--). – jaco0646 Apr 24 '18 at 22:19
  • Also note there's not a lot of benefit in [closing a StringReader](https://stackoverflow.com/questions/6122013/should-i-close-a-stringreader). – jaco0646 Apr 24 '18 at 22:23
  • @jaco0646 - Yes, Java 8 does make it a bit easier. I'll update my answer to show that. Thanks. As to closing the `StringReader`, that was just me on autopilot (closing any stream once I'm done with it). I'm surprised I didn't stick the whole thing into a `try/finally` statement. :) – Ted Hopp Apr 25 '18 at 02:42
5

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());

keiki
  • 3,260
  • 3
  • 30
  • 38
snakedoctor
  • 185
  • 2
  • 8
2

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");
Jherico
  • 28,584
  • 8
  • 61
  • 87
  • I had no success with this. Should i just try to split by last character before line break or somthing like that? – B. Money Nov 20 '12 at 01:07
  • If you had no success your input probably does not contain new lines. Perhaps you could post the contents of `result.getBytes()'? – Jherico Nov 20 '12 at 01:10
  • 5
    If you want to deal with all combinations of "\r" "\n" "\r\n" "\n\r" you can use: Splitter.on(CharMatcher.anyOf("\n\r")).omitEmptyStrings().split(yourstring); (note that this will also drop empty lines, which may or may not be what you want) – joe p May 20 '15 at 02:33
1
Matcher m = Pattern.compile("(^.+$)+", Pattern.MULTILINE).matcher(fieldContents);

while (m.find()) {
    System.out.println("whole group " + m.group())
}
blalasaadri
  • 5,990
  • 5
  • 38
  • 58
0

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");
anton
  • 247
  • 3
  • 13