Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java string question

Options
  • 17-08-2012 4:47pm
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,092 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,092 Mod ✭✭✭✭Tar.Aldarion


    That's great thanks.


Advertisement