0

I'm using a for loop to parse a string, like so:

for (int i = 1; i < s.length(); ++i)

The string is all lowercase, and if either the current character or previous character is not a letter, I want to avoid it, like so:

if (s.charAt(i) - 97 < 0 || s.charAt(i) - 97 > 25 || s.charAt(i-1) < 0 || s.charAt(i-1) > 25)
{
    continue
}

The first string I input is "marty," yet the if statement is registering true. I've confirmed that every single one of the four boolean values evaluates to false, yet the if statement itself is apparently true for every single letter in every single string.

I even made four separate bool variables, one for each parameter, confirmed they're all false, then OR'd them all together. Also false. Yet the if statement fires every single time.

I really don't know what I'm missing here. Can anyone help me?

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Don't use [magic numbers](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). – Pshemo Nov 17 '14 at 19:59

1 Answers1

3

You are using - 97 to subtract out 'a' so you can compare the character to the range 0-25. But you only did that for the first 2 conditions. Continue subtracting 97 for the last 2 conditions, which are on the "previous" character.

rgettman
  • 176,041
  • 30
  • 275
  • 357