MJ
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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);
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_n
int dot=s.lastIndexOf('.'),
idx1=s.lastIndexOf(java.io
if ((idx1>=0)&&(idx1>dot)) dot=-1; // no dot found after the last file separator
String ext=(dot<0)?"":s.substring
>> 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 :)
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.
<*>
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
Not true, read it again, there is a difference i mentioned in my comment : -1 if '.' is not found instead of 0
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);
}
<*>