Java似乎无法识别正斜杠

时间:2013-10-31 06:56:39

标签: java string character-encoding

我正在尝试计算网址中正斜杠的数量。

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

我有:

p.rint("Product");
p.rint(url);
p.rint(StringUtils.countMatches(URLDecoder.decode("url", "UTF-8"), "/"));

打印出看起来像的结果:

Product
http://stackoverflow.com/questions/ask
0

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

Note: p.rint() is my little hack for doing System.out.println()

我在不使用URLDecoder.decode()的情况下尝试了这个。

3 个答案:

答案 0 :(得分:6)

您正在计算常量字符串"url"的正斜杠,而您想要从名为url变量计算它们

答案 1 :(得分:5)

这是问题所在:

URLDecoder.decode("url", "UTF-8")

应该是:

URLDecoder.decode(url, "UTF-8")

否则你正在解码文字“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, "/"));

答案 2 :(得分:2)

试试这个:

p.rint("Product");
p.rint(url);
p.rint(StringUtils.countMatches(URLDecoder.decode(url, "UTF-8"), "/")); // pass varible url

您正在通过URL而不是http://stackoverflow.com/questions/ask

相关问题