Reputation: 745
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?
Upvotes: 2
Views: 15368
Reputation: 1073968
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"))
Upvotes: 15
Reputation: 81
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);
}
Upvotes: 3
Reputation: 33534
- 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.
Upvotes: 0