Question

public String extension(File F)
{
    String FileName = F.getName();
    int LastIndex = FileName.lastIndexOf(DotSymbol);
    if(LastIndex > 0 && LastIndex <FileName.length() -1)
    {
    return FileName.substring(LastIndex+1);
    }else 
    {
        return "";

I don't understand why I need to decrement 1 from the if statement and add a 1 to the substring.

Was it helpful?

Solution

You are finding the last position of the string that has a dot. If you find a dot then you will return the substring after the dot (this gets the file extension). You subtract one, because if the dot is the last character of the string you have no file extension. You add one, because you don't want to return the dot, you want to return what's after the dot (the file extension).

OTHER TIPS

The lastIndexOf() method returns -1 if the String passed as parameter is not found as a substring of FileName.

So, the check

if(LastIndex > 0 && LastIndex <FileName.length() -1)

doesn't make any sense to me.

I would have expected this instead:

if (LastIndex != -1)
    return FileName.substring(LastIndex+1);
else 
    return "";

As for the

return FileName.substring(LastIndex+1);

That depends on the context: what do you want to extract from FileName?

If you are trying to extract the file extension, then the +1 is needed to skip the occurrence of the . character found in the string.

References: String documentation

You remove 1 because lasiIndexOf return the position starting at 0.

You add 1 to remove the "." of the extension.

since the index of strings start from zero , and the last index will be the length of the string -1

The code is looking for .

The first check disregards files that start with a . as on *nix systems that denotes a special file or directory.

The substring() call adds 1 so that it returns everything after the ..

If would appear this is code meant to return file extensions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top