Eleminate a char in java string

how can i link the last one ,|

in this String

:

String model ="07:40,09:00,10:20,11:40,|09:00,10:20,11:40,|07:40,09:00,10:20,11:40,|10:20,11:40,|";

      

Model

is a variable String

and the result should look like this:

String result="07:40,09:00,10:20,11:40,|09:00,10:20,11:40,|07:40,09:00,10:20,11:40,|10:20,11:40";

      

+3


source to share


5 answers


If it's always there ,|

and you don't know if it will be used, use replaceFirst

:

model = model.replaceFirst(",\\|$", "");

      



PS $

marks end of line

+4


source


   String model ="07:40,09:00,10:20,11:40,|09:00,10:20,11:40,|07:40,09:00,10:20,11:40,|10:20,11:40,|";
   String result = model.substring(0, model.length() -2);
   System.out.println(result);

      



javadoc: substring (int beginIndex, int endIndex) : Returns a new string that is a substring of this string.

+3


source


If it always appears, you can strip the end of the line. For that you can use this code:

result = model.substring(0, path.length() - 2);

      

If this happens sometimes, you can do this:

if (model.substring(path.length - 2, path.length).equals(",|")) {
    result = model.substring(0, path.length() - 2);
} else {
    result = model
}

      

+3


source


Try StringUtils :

import org.apache.commons.lang3.StringUtils;

// model = "07:40,09:00,10:20,11:40,|09:00,10:20,11:40,|07:40,09:00,10:20,11:40,|10:20,11:40,|"
model = StringUtils.removeEnd(model, ",|");
// Now 
// model = "07:40,09:00,10:20,11:40,|09:00,10:20,11:40,|07:40,09:00,10:20,11:40,|10:20,11:40";

      

+2


source


String correctedModel=new StringBuilder(model).deleteCharAt(model.lastIndexOf('|')).toString();

      

Check documents StringBuilder.deleteChartAt () and String.lastIndexOf ()

+2


source







All Articles