• Post Reply Bookmark Topic Watch Topic
  • New Topic

I don't know how to use String trim  RSS feed

 
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
This morning I decided to learn Java . So here I am ;).
I have one problem with String.
Take a look:



The output is:
[ Hello there ]
[Hello there]
[ Hello there ]


I'm sure I'm doing something wrong . Can you tell me what? I would apreciate a link to some good tutorial that explains Strings .
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings are immutable.

s.trim() does not trim the string referenced by s, but rather returns a new string with the trimmed version of the original string.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch!
 
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

First thing about String you should know is that it is immutable, once created, that's it can't be changed.

Now on line 4 when you do "s.trim()", the result doesn't go anywhere hence on line printing s will be exactly the same as on line 3. Same goes for printing s on line 7.

On line 6 trimming s just before output actually manipulate the output string.

Oh about the trim function, it simple trim the spaces before and after, not the spaces in between.
 
Maria Kowalczyk
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SO I need to save new String to s

I did it

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Right: on line 4, you create a new string with the trimmed version of the original, and assign it to s.

Note that you have still not changed the value of the string, you have simply created a new one and changed which string s references.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!