如何消除此,|
中的最后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,|";
模型是变量String
,结果应该是这样的:
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";
答案 0 :(得分:4)
如果它总是,|
并且您不知道它是否会出现,请使用replaceFirst
:
model = model.replaceFirst(",\\|$", "");
P.S。 $
代表String的结尾
答案 1 :(得分:3)
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): 返回一个新字符串,它是该字符串的子字符串。
答案 2 :(得分:3)
如果这总是出现,你可以剪掉字符串的结尾。为此,您可以使用此代码:
result = model.substring(0, path.length() - 2);
如果只是偶尔发生,你可以这样做:
if (model.substring(path.length - 2, path.length).equals(",|")) {
result = model.substring(0, path.length() - 2);
} else {
result = model
}
答案 3 :(得分:2)
尝试 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";
答案 4 :(得分:2)
String correctedModel=new StringBuilder(model).deleteCharAt(model.lastIndexOf('|')).toString();