cat_bug cat_bug - 9 days ago 4
Java Question

String of last 2 items in colon separated string

So I have a string = "ab:cd:ef:gh"
I want to return a string = "ef:gh" (third colon intact).
Or "apple:orange:cat:dog" returns "cat:dog" (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 was wondering if there's something a little easier.


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]);