2

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
DreamsOfHummus
  • 735
  • 2
  • 7
  • 18
  • It's not clear why you think `endsWith` isn't working. Why would you expect it to return `true` in this case? – Jon Skeet Nov 25 '12 at 19:17

3 Answers3

15

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"))
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Hy. I think this is what you want:

    String str = "http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP";
    //String str = "http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF";
    if (!str.startsWith("http://")) { // correct forgetting to add 'http://'
        str = "http://" + str;
    }
    System.out.println(str);
    if (!str.endsWith(".PDF")) {
        str = str + ".PDF";
    }
    System.out.println(str);
}
Alex
  • 81
  • 5
0

- Its simply because your String http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF doesNot ends with \Q.PDF\E

- If you are concerned with matching the .PDF, then do this...

if (s.endsWith(".PDF")){

  // add it at the end....

}

- It would be more appropriate to use StringBuilder here instead of String, which is mutable.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75