Java似乎无法识别正斜杠

Ank*_*kur 0 java string character-encoding

我试图计算URL中正斜杠的数量.

但是Java和StringUtils似乎不想这样做.我怀疑它与编码有关,但使用URLDecoder似乎没有帮助.

我有:

p.rint("Product");
p.rint(url);
p.rint(StringUtils.countMatches(URLDecoder.decode("url", "UTF-8"), "/"));
Run Code Online (Sandbox Code Playgroud)

其中打印出的结果如下:

Product
http://stackoverflow.com/questions/ask
0
Run Code Online (Sandbox Code Playgroud)

如果一切按预期工作,那么打印输出的最后一行肯定应该4......

Note: p.rint() is my little hack for doing System.out.println()
Run Code Online (Sandbox Code Playgroud)

我没有使用URLDecoder.decode()也试过这个.

Ahm*_*leh 6

您正在计算常量 String 的正斜杠"url",而您希望从名为的变量中计算它们url

  • 哇,我得到的答案比Jon Skeet更多......这是真实的:O (2认同)

Jon*_*eet 5

这就是问题:

URLDecoder.decode("url", "UTF-8")
Run Code Online (Sandbox Code Playgroud)

那应该是:

URLDecoder.decode(url, "UTF-8")
Run Code Online (Sandbox Code Playgroud)

否则你正在解码文字"url" - 它将解码为自身("url") - 字符串"url"不包含任何斜杠.据推测,你实际上对url变量的价值感兴趣.

下一次,帮助诊断这个问题的一种简单方法是StringUtils.countMatches通过另一个局部变量将您担心的方法()与所有其他评估隔离开来:

p.rint("Product");
p.rint(url);
String decodedUrl = URLDecoder.decode(url, "UTF-8");
p.rint(decodedUrl);
p.rint(StringUtils.countMatches(decodedUrl, "/"));
Run Code Online (Sandbox Code Playgroud)