消除 String java 中的一个字符
Eleminate a char in String java
我怎样才能消除这个 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";
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.
如果总是出现这种情况,您可以切断字符串的末尾。为此,您可以使用此代码:
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
}
如果它总是 ,|
而您不知道它是否会出现,请使用 replaceFirst
:
model = model.replaceFirst(",\|$", "");
P.S。 $
代表字符串结束
试试 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";
String correctedModel=new StringBuilder(model).deleteCharAt(model.lastIndexOf('|')).toString();
我怎样才能消除这个 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";
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.
如果总是出现这种情况,您可以切断字符串的末尾。为此,您可以使用此代码:
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
}
如果它总是 ,|
而您不知道它是否会出现,请使用 replaceFirst
:
model = model.replaceFirst(",\|$", "");
P.S。 $
代表字符串结束
试试 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";
String correctedModel=new StringBuilder(model).deleteCharAt(model.lastIndexOf('|')).toString();