Win a copy of Machine Learning with R: Expert techniques for predictive modeling this week in the Artificial Intelligence and Machine Learning 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
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

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: 4277
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.
 
Does this tiny ad smell okay to you?
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!