Java seems to not recognise forward slash

I am trying to count the number of forward slashes in a URL.

However Java and StringUtils don't seem to want to do this. I suspected it was related to encoding but using URLDecoder doesn't seem to help.

I have:

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

Which prints out results that look like:

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

If everything works as I am expecting, surely the last line of the printout should be 4 ...

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

I have tried this without using URLDecoder.decode() as well.

Jon Skeet
people
quotationmark

This is the problem:

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

That should be:

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

Otherwise you're decoding the literal "url" - which will decode to itself ("url") - and the string "url" doesn't contain any slashes. Presumably you're actually interested in the value of the url variable instead.

For next time, a simple way of helping to diagnose this would be to isolate the method you're worried about (StringUtils.countMatches) from all other evaluations, via another local variable:

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

people

See more on this question at Stackoverflow