[英]remove the last part of a string in java
String Y="part1 part2 part3",X="part1";
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = useSplitToRemoveLastPart(Y);
if(Y.equals("")) {
break;
}
}
//implementation of useSplitToRemoveLastPart() // useSplitToRemoveLastPart()的实现
private static String useSplitToRemoveLastPart(String y) {
//What goes here .. It should chop the last part of the string..
return null;
}
Can anyone help ... 谁能帮忙......
If you want part3 to be removed and provided that all the words are separated by space 如果您希望删除part3并提供所有单词由空格分隔
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
If you really want to use split: 如果你真的想使用split:
private static String useSplitToRemoveLastPart(String str) {
String[] arr = str.split(" ");
String result = "";
if (arr.length > 0) {
result = str.substring(0, str.lastIndexOf(" " + arr[arr.length-1]));
}
return result;
}
public String removeLastSubstring(String target, String toRemove){
int idx = target.lastIndexOf(toRemove);
target = target.substring(0, idx) + target.substring(idx + toRemove.length());
return target;
}
You only need to pass it your target and the LAST substring you want to remove, example: 您只需要将目标和要删除的LAST子字符串传递给它,例如:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");
Your whole code can be optimized to: 您的整个代码可以优化为:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
If you want to do it using split , then you can do: 如果你想使用split进行 ,那么你可以这样做:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.