문제

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?

도움이 되었습니까?

해결책

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"))

다른 팁

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);
}

- 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top