0

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.

  • Why can't you use regex? – shmosel May 31 '23 at 20:50
  • 1
    You can use `str = str.substring(0, str.substring(0, str.lastIndexOf('/')).lastIndexOf('/'));`. By the way, I would prefer a regex solution (as already shown by shmosel. – Arvind Kumar Avinash May 31 '23 at 21:13
  • "_trying to split by "/" ... but stuck in middle_" - Can you show us your code and what happens when you run it? You may already be very close to a solution and it may be helpful to you, to see how to fix what you already have (assuming none of the existing answers already do that). – andrewJames May 31 '23 at 23:07

4 Answers4

2

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));
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
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) : "";
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

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
Reilas
  • 3,297
  • 2
  • 4
  • 17