• Post Reply Bookmark Topic Watch Topic
  • New Topic

Checking and removing non-letter Characters from both ends of a String  RSS feed

 
Ranch Hand
Posts: 33
1
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I'm trying to read in words from a file and remove any non-letter chars from either or both ends of each word.  I thought a while loop would do this, but I'm getting unexpected results.  I'm trying to use a while loop because I've seen instances of two non-letter chars beginning a word.  However, it seems what the code is actually doing is whittling down each word to nothing.  Doesn't the while loop check each iteration if the firstChar isn't a letter or digit?  Maybe I don't understand a while loop?

Thank you!



Here's the output from the console:

 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You never update the firstChar variable.
So, if the character at index 0 is not a letter or digit then the loop never stops until the string is too short and an invocation of substring throws an exception.
 
Dustin Wright
Ranch Hand
Posts: 33
1
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paweł Baczyński wrote:You never update the firstChar variable.
So, if the character at index 0 is not a letter or digit then the loop never stops until the string is too short and an invocation of substring throws an exception.


Thank you!  I see that now.
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you need to include a length check inside your loop in case all characters are non-alphanumeric.
 
Dustin Wright
Ranch Hand
Posts: 33
1
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!  It appears to be in order now.  I suspect this could be written more compactly.  Please bear with me, I'm very much a novice.

 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is almost correct.
Please verify this method call cleanWord("---");
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!