cat_bug cat_bug - 1 month ago 14
Java Question

How to find a String of last 2 items in colon separated string

I have a string =

ab:cd:ef:gh
. On this input, I want to return the string
ef:gh
(third colon intact).

The string
apple:orange:cat:dog
should return
cat:dog
(there's always 4 items and 3 colons).


I could have a loop that counts colons and makes a string of characters after the second colon, but I was wondering if there exists some easier way to solve it.

Answer

You can use the split() method for your string.

String example = "ab:cd:ef:gh";
String[] parts = example.split(":");
System.out.println(parts[parts.length-2] + ":" + parts[parts.length-1]);