java 在java中删除字符串的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5408796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove the last part of a string in java
提问by Praneel PIDIKITI
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 ...
谁能帮忙...
回答by Jigar Joshi
If you want part3 to be removed and provided that all the words are separated by space
如果您想删除第 3 部分并提供所有单词以空格分隔
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
回答by lukastymo
If you really want to use 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;
}
回答by Alpha2k
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:
您只需要将您的目标和要删除的最后一个子字符串传递给它,例如:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");
回答by Ingo
Your whole code can be optimized to:
您的整个代码可以优化为:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
回答by abahgat
回答by MByD
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;