Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Split A String By Line Break? [duplicate]

Tags:

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

like image 527
B. Money Avatar asked Nov 20 '12 00:11

B. Money


People also ask

How do I split a string by next line?

To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' . A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence. You can also split a string on the system-dependent line separator string.

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.


1 Answers

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

   String textStr[] = yourString.split("\\r\\n|\\n|\\r"); 
like image 157
RajeshVijayakumar Avatar answered Sep 22 '22 04:09

RajeshVijayakumar