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

Android Build a Self-Destructing Message Android App Adding Users Using Parse.com Error Messages with Dialogs

What does trim do and why are we using it on all fields including password?

I tried to test the trim() method:

String test = "    Four spaces before  two spaces before    four spaces before";
                String testTrim = test.trim();
                Log.v(TAG, test);
                Log.v(TAG, testTrim);  //I first replaced testTrim with test.trim() and got the same result

and got this in the log:

V/SignUpActivity Four spaces before  two spaces before    four spaces before
V/SignUpActivity Four spaces before  two spaces before    four spaces before

It seems that it didn't get rid of any spaces, which brings me to my next question: If it did in fact remove spaces, why would we use it on the password field; especially without specifying that the password must not include spaces? Wouldn't this result in the user setting a password with spaces and having it checked against the password stored on the backend that has no spaces? I can understand that if the trim method is used before the check, you should match the string stored on the backend and be authenticated, but then doesn't this also mean that adding in spaces will not affect authentication so long as you have the same character sequence? Wouldn't " password", "p a ssword" and "password " all be authenticated?

1 Answer

Ben Junya
Ben Junya
12,365 Points

The trim() method is super handy and it's very helpful for all input fields.

trim() just removes any whitespace at the beginning and end of a string. This is why the spaces in the middle are still there.

If your input is " John Smith " Trimming this string would yield:

"John Smith"

It's very common for custom Android keyboards like SwiftKey to add a space at the end of any autocompleted string, so trimming prevents the sent data from any unnecessary whitespace.

Very interesting! That makes a lot of sense. If you look back at my code I printed test and testTrim to the log. I'm curious as to why test didn't appear with the spaces before the entry. Does the log implement a trim method of its own? Anyway thanks for the answer!