Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java string question

  • 17-08-2012 04:47PM
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,119 Mod ✭✭✭✭


    I was jsut trying to find the last occurrence of a period in a string, and returning the substring after this period. I was thinking of using lastIndexOf, which would be simplest? That works fine but if there is no period in the string it returns the whole string. What is the best way to check if there is no occurrence of a period in the string? I have:
    if(str.matches(".*\\..*"))
    

    That seems a bit much, shouldn't lastIndexOf just be returning -1 and not the whole string if it doesn't find an instance of period?
    The same thing happens with String.Split. So please tell me why I am stupid!


Comments

  • Closed Accounts Posts: 8,015 ✭✭✭CreepingDeath


    I'd write a little utility method like this
        public static String afterDot(String str)
        {
            int lastDot = str.lastIndexOf('.');
            return ( lastDot!=-1 ? str.substring(lastDot+1) : "" );
        }
    


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,119 Mod ✭✭✭✭Tar.Aldarion


    That's great thanks.


Advertisement