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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Java string question

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


    That's great thanks.


Advertisement