Vikram Vikram - 1 year ago 56
Java Question

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

I have my string defined as


I want to get output as


using String methods.

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

Is there a better way to achieve this?

Answer Source

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() ? : 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);
    return lastIndex >= 0 ? input.substring(0, lastIndex) : null;

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