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("")) {
开发者_JAVA百科 break;
}
}
//implementation of 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
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
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;
}
Your whole code can be optimized to:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
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#");
If you want to do it using split, then you can do:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;
By the way, If the method you need to build is called useSplitToRemoveLastPart(String t)
, then I'd suggest you to use split to remove last part.
Take a look here.
精彩评论