To remove last two words from a string

67 views Asked by At

I have sample strings like below,

abc/def/ghi/test/yvw/syz

abc/fed/igh/test_123/wuvacv/zyxh

I want to get it like below

abc/def/ghi/test

abc/fed/igh/test_123

So what are the best way to follow for string manipulation

Thanks in advance.

I'm trying to split by "/" and put the words into an array and looping it.but stuck in middle. Here I cant use regex here cas last two words can be anything.

4

There are 4 answers

2
shmosel On

You can use a simple regex to match any text between the slashes:

str = str.replaceAll("/[^/]+/[^/]+$", "");

Or you can split and rejoin like this:

String[] parts = str.split("/");
str = String.join("/", Arrays.asList(parts).subList(0, parts.length - 2));
0
Elliott Frisch On

I would use String.lastIndexOf(String, int) to search for the second to last / and then take the substring. Like

String[] arr = {
        "abc/def/ghi/test/yvw/syz", 
        "abc/fed/igh/test_123/wuvacv/zyxh"
};
for (String s : arr) {
    int p = s.lastIndexOf("/", s.lastIndexOf("/") - 1);
    System.out.println(s.substring(0, p));
}

Outputs (as requested)

abc/def/ghi/test
abc/fed/igh/test_123
0
Oleg Cherednik On
public static String removeLastTwoWords(String str) {
    String[] words = StringUtils.split(str, '/');
    return String.join("/", ArrayUtils.subarray(words, 0, words.length - 2));
}

In case you do not want to split a string, you could use lastIndexOf():

public static String removeLastTwoWords(String str) {
    int last = str.lastIndexOf('/');
    int preLast = str.lastIndexOf('/', last - 1);
    return preLast > 0 ? str.substring(0, preLast) : "";
}
0
Reilas On

There are a few approaches you can take.

Keep in mind, the String#split parameter is a regular expression pattern.

To create a loop that iterates on a String#split you can use the following.
It will stop iterating when it reaches the second to last element—using a fixed condition of strings.length - 2.

String parse(String string) {
    StringBuilder parsed = new StringBuilder();
    String[] strings = string.split("/");
    for (int index = 0; index < strings.length - 2; index++) {
        if (index != 0) parsed.append("/");
        parsed.append(strings[index]);
    }
    return parsed.toString();
}

Output

abc/def/ghi/test
abc/fed/igh/test_123

If you would prefer to provide a starting and limiting index, you can implement additional method parameters.
The limit argument will be inclusive.

/** @param limit inclusive */
String parse(String string, int startIndex, int limit) {
    StringBuilder parsed = new StringBuilder();
    String[] strings = string.split("/");
    for (int index = startIndex; index <= limit; index++) {
        if (index != 0) parsed.append("/");
        parsed.append(strings[index]);
    }
    return parsed.toString();
}

Here is an example input and output.

String stringA = "abc/def/ghi/test/yvw/syz";
String stringB = "abc/fed/igh/test_123/wuvacv/zyxh";
System.out.println(parse(stringA, 0, 3));
System.out.println(parse(stringB, 0, 3));
abc/def/ghi/test
abc/fed/igh/test_123

Finally, if your string value follows the same pattern, in which the contained value always starts at index 0, and ends on the first-to-last solidus character, you can utilize the String#substring and String#lastIndexOf methods.

The second parameter of the lastIndexOf call, here, is an offset index.
So, it is locating the last solidus character, and then using the returned index as an offset of another call.

String string = "abc/def/ghi/test/yvw/syz";
int indexOf = string.lastIndexOf('/', string.lastIndexOf('/') - 1);
string = string.substring(0, indexOf);
abc/def/ghi/test