Vikram Vikram - 4 months ago 16
Java Question

How to display the characters upto a specific index of a String using String function?

I have my string defined as


text1:text2:text3:text4:text5


I want to get output as


text1:text2:text3


using String methods.

I have tried using
lastIndexOf
, then
substring
and then again
lastIndexOf
.
I want to avoid these three steps with calling
lastIndexOf
two times.

Is there a better way to achieve this?

Answer

A regular expression could be used to identify the correct part of the string:

private static Pattern PATTERN = Pattern.compile("([^:]*:){2}[^:]*(?=:|$)");

public static String find(String input) {
    Matcher m = PATTERN.matcher(input);
    return m.find() ? m.group() : null;
}

Alternatively do not use substring between every call of lastIndexOf, but use the version of lastIndexOf that restricts the index range:

public static String find(String input, int colonCount) {
    int lastIndex = input.length();
    while (colonCount > 0) {
        lastIndex = input.lastIndexOf(':', lastIndex-1);
        colonCount--;
    }
    return lastIndex >= 0 ? input.substring(0, lastIndex) : null;
}

Note that here colonCount is the number of : that are left out of the string.

Comments