Link to home
Start Free TrialLog in
Avatar of g118481
g118481

asked on

How to trim this?

How can I trim this string?  
It has a space at the end.

<%
String username1 = (String)session.getAttribute("j_username");
%>
ASKER CERTIFIED SOLUTION
Avatar of Weiping Du
Weiping Du
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kaliyugkaarjun
kaliyugkaarjun


<%
String username1 = (String)session.getAttribute("j_username");
username1.trim(); //now username contains  string without trailing space

%>
SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
muktajindal, your first suggestion is not as elegant as karanw's (imho)

and your second one gives me the fear ;-)
In karanw's solution, he has suggested to check for null in second statement whereas a NullPointerException will be thrown in the first statement itself if session.getAttribute("j_username") is null.

My second solution is for the case when developer is sure that session.getAttribute("j_username") is never null and contains exaclty one space at the end (as he has mentioned in the question " How can I trim this string? It has a space at the end. ")
>> whereas a NullPointerException will be thrown in the first statement itself if session.getAttribute("j_username") is null.

No it won't

String s = (String)null ;

is fine

Fair enough about the second bit though :-)  It just worries me that trimming for such a specific case will require updating later when a space occurs at the beginning, or another space appears at the end ;-)
Yeah, I'm sorry for the first part. But for the second one, it depends what level of flexibility the developer wants to have in his application. according to his question, its OK.
I agree :-)

Sorry for sounding grumpy...  I think I hadn't woken up properly yet :-(

Cheers,

Tim