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
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 to share
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 to share
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 to share
String correctedModel=new StringBuilder(model).deleteCharAt(model.lastIndexOf('|')).toString();
Check documents StringBuilder.deleteChartAt () and String.lastIndexOf ()
+2
source to share