Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

trim method

 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Execute the program like java StringTest1 alpha beta
Output:
Argbeta
Arg beta

Question: Why the trim method is not removing the trailing whitespaces in String s2.
 
Michael Imhof
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're looking at the API doc for java.lang.String (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html)
you'll find the definition for the method trim():
"Returns a copy of the string, with leading and trailing whitespace omitted."

So in your example this means:



" Arg ".trim() will return a new String "Arg" and will be saved
in s1.



" Arg " + args[1] is a new String " Arg Beta" and will be saved in s2.
" Arg Beta".trim will return a new String "Arg Beta" and
will be saved in s2.

Correct output is:
ArgBeta

Arg Beta

Mike
 
Krishna Srinivasan
Ranch Hand
Posts: 1874
Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this will work:

String2 you are appending string and using trim method.

String s2 = " Arg "+arg[1] ;
There is no space for triming.

class StringTest1 {
public static void main(String[] args) {
String s1 = " Arg ";
s1= s1.trim();
System.out.println(s1+ args[1] );
System.out.println();

String s2 = " Arg " ;
s2= s2.trim();
System.out.println(s2+args[1]);

}
}
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic