String character compare function?

classic Classic list List threaded Threaded
2 messages Options
jrd
Reply | Threaded
Open this post in threaded view
|

String character compare function?

jrd
In my current Jack same project, I need to compare String characters as part of a word game.

However, I notice that the String class doesn't include a specific function/method for comparing characters - like many object oriented languages.

So, assuming I've properly defined:

field String test;
let test = String.new("forever");

And, if test.charAt(2) returns "r", then...

** In Jack, will this expression below evaluate as true in comparing characters?

if (test.charAt(2) = "r")....

Does that syntax work properly substituting for a hypothetical String.compareTo function?

Pls let me know any thoughts.  Thx,



Reply | Threaded
Open this post in threaded view
|

Re: String character compare function?

cadet1620
Administrator
You need to compare characters to the integer "character code" which is the ASCII value of the character.  For example,
    if (test.charAt(2) = 114) {    // "r"
I like to put the actual character in the comment as shown.


Here's a handy table to get the character codes:
                          1 1 1 1 1 1 1 1 1 1
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
     ----------------------------------------
 20 |                           ! " # $ % & '
 40 | ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ;
 60 | < = > ? @ A B C D E F G H I J K L M N O
 80 | P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c
100 | d e f g h i j k l m n o p q r s t u v w
120 | x y z { | } ~
space is character code 32.
For other characters, add the row and column number. For example: 'r' is 100 + 14 = 114.


Note the the Keyboard always returns uppercase characters A-Z. Also, there are character codes for the following special keyboard keys:
newline      128       end        135
backspace    129       page up    136
left arrow   130       page down  137
up arrow     131       insert     138
right arrow  132       delete     139
down arrow   133       esc        140
home         134       f1–f12     141–152

--Mark