-4

I want to select specific substring from the input string:

String i = "example/test/foo-foo";

How to get only the substring foo-foo as a new string?

Expected output:

String newString = "foo-foo";
Yasas Gunarathne
  • 833
  • 1
  • 6
  • 19
Ari Wibowo
  • 83
  • 4
  • 11

2 Answers2

0

Best way to do this is through a utility class since we can reuse the code with this approach. Furthermore some corner cases can be handled to avoid runtime exceptions.

public class StringUtils {
    public static final String EMPTY = "";

    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        }
        if (isEmpty(separator)) {
            return EMPTY;
        }
        int pos = str.lastIndexOf(separator);
        if (pos == -1 || pos == (str.length() - separator.length())) {
            return EMPTY;
        }
        return str.substring(pos + separator.length());
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

Then create your newString using,

String newString = StringUtils.substringAfterLast(i, "/");

Yasas Gunarathne
  • 833
  • 1
  • 6
  • 19
0

There are many options to solve that. For example via regex search/replace or the substring methods of class String.

Regex approach:

Optional<String> resultA = Optional.of(string.replaceAll("^.*/([^/]+)$", "$1"));

Substring approach:

int start = string.lastIndexOf('/');
Optional<String> resultB = Optional.of(start > 0 && start + 1 < string.length() ? string.substring(start) : null);

There are plenty of more elaborate solutions for this problem on stackoverflow btw., so you might be better off with a thorough stackoverflow search.

lher
  • 126
  • 7