String.endsWith() not working

DreamsOfHummus picture DreamsOfHummus · Nov 25, 2012 · Viewed 12.4k times · Source

I have the following string

http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF

I want it so if the user forgets to input the http:// or the .PDF, the program will automatically correct this. Therefore, I tried this code

if (!str.startsWith("http://")) { // correct forgetting to add 'http://'
        str = "http://" + str;
    }
    System.out.println(str);
    if (!str.endsWith("\\Q.PDF\\E")) {
        str = str + "\\Q.pdf\\E";
    }

However, even when I enter the correct string, http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF the output is this.

http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF\Q.pdf\E

Why? Why is another '.PDF' being added?

Answer

T.J. Crowder picture T.J. Crowder · Nov 25, 2012

Because http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF doesn't have a \Q.PDF\E on the end. In a string literal, \\ gives you a backslash. So "\\Q.PDF\\E" is \Q.PDF\E — a backslash, followed by a Q, followed by a dot, followed by PDF, followed by another backslash, followed by E.

If you want to see if the string ends with .PDF, just use

if (!str.endsWith(".PDF"))

Of course, that's case-sensitive. If you want it to be case-insensitive, probably:

if (!str.toLowerCase().endsWith(".pdf"))