简体   繁体   中英

Check if ASCII Code Value Of Character In String Is Greater Than or Less Than ASCII Code Value of Previous Character - JavaScript

Attempting this problem on codewars .

The function should return true if the characters in the string appear in order.

For example:

solve("abc") = True, because it contains a,b,c

solve("abd") = False, because a, b, d are not consecutive.

solve("dabc) = True, because it contains a, b, c, d

solve("abbc") = False, because b does not occur once.

solve("v") = True

My thought is to check if the next character in the string has an ASCII code value that is greater than the ASCII code value of the previous character.

If this is the case, return true. Otherwise, return false.

I have:

function solve(s){
  for (let i = 0; i < s.length; i++) {
    let character = s[i];
    //if character ASCII value is > than the ASCII value of character before it
    if (character.charCodeAt(0) > /*previous character.charCodeAt(0));*/ ) {
      return true
    }
    else {
      return false;
    }
  }
}

But as you can see, I don't know how to make a comparison to the previous character.

You have a few issues in your code.

  1. You aren't comparing the right content in your if clause. You are comparing the same thing. You need to check if the next char code index is greater than your current.

  2. You are immediately returning after the first character because you return true off top without looping through the values.

Make sure to pay attention when you are looping, your biggest issue is you are just straight comparing the same char over and over because you stop worrying about the index of the char you are checking.

I would say basically in your function if the next char code is less than the current return false, otherwise return true. This will only return true after looping through the entire string.

 function solve(s){ s = s.trim().split("").sort().join(""); // remove white spaces, split to sort and then join again for (let i = 0; i < s.length - 1; i++) { if ((s.charCodeAt(i + 1) - s.charCodeAt(i)) !== 1) { return false; } } return true; } console.log(solve('abcdef')); //true console.log(solve('afew')); //false console.log(solve('defghijklmn')); //true console.log(solve('lkjsadf')); //false console.log(solve('123456')); //true console.log(solve('123abc')); //true console.log(solve('abc123')); //false console.log(solve('abd')); //false console.log(solve('abbc')); //false console.log(solve('abc')); //true console.log(solve('dabc')); // true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM