Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java String Keep Whitespace

Hi Everyone

I'm attempting to keep the whitespace in a URL. I've tried replaceAll(), replace() and split() methods but I'm getting "invalid escape sequence"

   theID.replace("\s", "%20";)
   theID.split("\s");
   theID.replaceAll("\s", "%20");

I'm attempting to find the white space and replace it with "%20". How would I do that?

Thanks

2 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Hi Shane!

I'm thinking this will help:

http://stackoverflow.com/questions/10786042/java-url-encoding

That way the replacing happens for you and you don't need to think about all the different options.

Let me know if you can't use that for some reason.

Hope it helps!

Hi Craig

Thanks, I appreciate the help but I went about it in a slightly different way. I created a method that ads whitespace in-between the parameters I'm passing.

I passed two string parameters into my method and I returned them as a string array. I'm not entirely sure if this was the correct way to do it but it's working well for me. I've pasted my syntax below. Tell me what you think?

        String result[] = createTheWhiteSpaceBetweenParameters(para1, para2);
        String theURL = "http://mywebsite.com/myURL.php? locID="+result[0]+"&statID="+result[1]; // my URL

        // method
    public String[] createTheWhiteSpaceBetweenParameters(String a, String b){
        Pattern pattern = Pattern.compile("\\s");
        Matcher matcher = pattern.matcher(a);
        Matcher matcher2 = pattern.matcher(b);

        String theIDForUrlS = matcher.replaceAll("%20");
        String theIDForUrlC= matcher2.replaceAll("%20");

        return new String[] {theIDForUrlS, theIDForUrlC};
    }
Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

The problem with that approach is that there are more things to escape that will bite you, like commas, equals, and unicode.

I've used this before: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIBuilder.html

addParameter and setParameters are similar to what you are doing, they take unescaped values and escape them for you.

Hope it helps!