Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

Detect if String has "." and how many characters after it??

How do I detect if String has "." and how many characters after it??

For example :

1234.123

would tell me it has a period and has 3 characters after the period. Can be done in multiple step.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sciuriware
sciuriware

This code fails if there is no dot ...................
It should read:

int dot = s.indexOf(".");
int after = (dot < 0) ? 0 : (s.length() - dot - 1);

If you are after the extension of a filename:
String extension = "";
int dot = s.indexOf('.');
if(dot >= 0)
{
     extension = s.substring(dot);
}

<*>
Hi 894359,

If you want a different value when there is no period character ( -> -1 ) and when there is 0 characters after the period ( -> 0 ) :

int dot = s.indexOf('.');
int after = (dot < 0) ? -1 : (s.length() - dot - 1);

Also, if you want the file extension, you have to use lastIndexOf instead of indexOf, and detect the last file separator also (for example in   C:\my_directory.ext\file_no_extension ) :

int dot=s.lastIndexOf('.'),
     idx1=s.lastIndexOf(java.io.File.separatorChar); // or '/'

if ((idx1>=0)&&(idx1>dot)) dot=-1; // no dot found after the last file separator

String ext=(dot<0)?"":s.substring(dot+1);
>> This code fails if there is no dot ...................

Not necessarily ;-) the value of 'after', if negative, means that the 'dot' was not found so the code doesn't fail :)
Webstorm, you just copied by answer,
mayankeagle, when there's no dot 'after' should be 0 and not negative.
<*>
Actually, on second thought, it would be positivie :) and equal to the length of the String, I guess.
>> Webstorm, you just copied by answer
Not true, read it again, there is a difference i mentioned in my comment : -1 if '.' is not found instead of 0