• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 246
  • Last Modified:

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.
0
894359
Asked:
894359
  • 3
  • 2
  • 2
  • +1
1 Solution
 
objectsCommented:
int dot = s.indexOf(".");
int after = s.length() - dot - 1;
0
 
sciuriwareCommented:
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);
}

<*>
0
 
WebstormCommented:
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);
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
WebstormCommented:

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);
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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 :)
0
 
sciuriwareCommented:
Webstorm, you just copied by answer,
mayankeagle, when there's no dot 'after' should be 0 and not negative.
<*>
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Actually, on second thought, it would be positivie :) and equal to the length of the String, I guess.
0
 
WebstormCommented:
>> 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
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now