Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove the last part of a string in java

Tags:

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()

private static String useSplitToRemoveLastPart(String y) {

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

 }

Can anyone help ...

like image 452
Praneel PIDIKITI Avatar asked Nov 28 '22 06:11

Praneel PIDIKITI


2 Answers

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(" "));
like image 166
jmj Avatar answered Dec 01 '22 00:12

jmj


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;

}
like image 32
lukastymo Avatar answered Nov 30 '22 22:11

lukastymo