Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

Issue with parsing Strings?

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, I'm parsing data from a .txt file:



For some reason, when I use the trim() method, it only trims the first whitespace.

" Benjamin "

Result:

"Benjamin "

But I can never get rid of the last whitespace? I've tried the replaceAll(" ", ""); method. Doesn't work. There isn't any hanging whitespaces in the code OR in the .txt file
 
Rancher
Posts: 4588
47
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're printing out the value of result[0]...that hasn't been trimmed.
The trimmed values are in the Player instance.
 
Bartender
Posts: 3323
86
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling .trim() doesn't trim the String object it is called on (Strings are immutable), it returns a copy of the String which is trimmed. So your code is passing a trimmed version of result[0] to the Player constructor but printing out the original untrimmed version.
 
Tony Docherty
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
8 seconds too late - well done Dave.

Alternatively you could split the string using "\s*/\s*" which will split the string and effectively trim the separate strings in one go
 
Ben Jass
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh wow. Didn't even think about that guys, really appreciate the help.
 
No thanks. We have all the government we need. This tiny ad would like you to leave now:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic