B. Money B. Money - 1 year ago 119
Java Question

How Do I Split A String By Line Break?

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";
return result;

result.getCoin reads as this:


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:

charlie some text"

instead of my desired output of:

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

Any help is greatly appreciated

Answer Source

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

   String textStr[] = yourString.split("\\r\\n|\\n|\\r");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download