java String.endsWith() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13554476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.endsWith() not working
提问by NightStrider
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
我想要它,所以如果用户忘记输入 http:// 或 .PDF,程序会自动更正。因此,我尝试了此代码
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
输出也是这样。
http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF\Q.pdf\E
Why? Why is another'.PDF' being added?
为什么?为什么要添加另一个“.PDF”?
回答by T.J. Crowder
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
.
因为最后http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF
没有\Q.PDF\E
。在字符串文字中,\\
给你一个反斜杠。因此"\\Q.PDF\\E"
是\Q.PDF\E
-一个反斜杠,随后Q
,后面跟着一个点,之后PDF
,紧接着又反斜杠,其次是E
。
If you want to see if the string ends with .PDF
, just use
如果您想查看字符串是否以 结尾.PDF
,只需使用
if (!str.endsWith(".PDF"))
Of course, that's case-sensitive. If you want it to be case-insensitive, probably:
当然,这是区分大小写的。如果您希望它不区分大小写,可能:
if (!str.toLowerCase().endsWith(".pdf"))
回答by Alex
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);
}
回答by Kumar Vivek Mitra
-Its simply because your String http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF
doesNotends with \Q.PDF\E
-这仅仅是因为你的字符串http://store.aqa.org.uk/qual/newgcse/pdf/AQA-4695-W-SP.PDF
不以\Q.PDF\E
-If you are concerned with matching the .PDF, then do this...
-如果您担心匹配 .PDF,那么请执行此操作...
if (s.endsWith(".PDF")){
// add it at the end....
}
-It would be more appropriate to use StringBuilder
here instead of String
, which is mutable.
-StringBuilder
在这里使用而不是更合适String
,因为它是可变的。