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