Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Issue with parsing Strings?  RSS feed

 
Ben Jass
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
 
Dave Tolls
Rancher
Posts: 2914
36
  • 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.
 
Tony Docherty
Bartender
Posts: 3268
82
  • 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: 3268
82
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!