删除java中字符串的最后一部分

时间:2011-03-23 16:50:17

标签: 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;
        }
    }

// useSplitToRemoveLastPart()的实现

private static String useSplitToRemoveLastPart(String y) {

  //What goes here .. It should chop the last part of the string..
return null;

 }

任何人都可以帮忙......

6 个答案:

答案 0 :(得分:21)

如果您希望删除part3并提供所有单词以空格分隔

String str ="part1 part2 part3";

String result = str.substring(0,str.lastIndexOf(" "));

答案 1 :(得分:3)

如果你真的想使用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;

}

答案 2 :(得分:1)

您的整个代码可以优化为:

boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";

答案 3 :(得分:1)

public String removeLastSubstring(String target, String toRemove){
    int idx = target.lastIndexOf(toRemove);
    target = target.substring(0, idx) + target.substring(idx + toRemove.length());
    return target;
}

您只需要将目标和要删除的LAST子字符串传递给它,例如:

String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");

答案 4 :(得分:0)

如果你想使用split 来做,那么你可以这样做:

String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
        n+= s[i];
return n;

答案 5 :(得分:0)

顺便说一句,如果您需要构建的方法名为useSplitToRemoveLastPart(String t),那么我建议您使用拆分删除最后一部分

看看here