String Compare does not work

Hi,

I am despaired. I can't get the string compare get running.

I have coded the following:

var stringArray = string.toCharArray();
for (var i = 0; i < stringArray.size(); i += 1) {
numberArray= string2Number(stringArray);
}

function string2Number(char) {
if (char.equals("1")) { return 1;}
if (char.equals("2")) { return 2;}
if (char.equals("3")) { return 3;}
if (char.equals("4")) { return 4;}
.....
if (char.equals("A")) {return 10;}
return 0;
}
[/CODE]

Unfortunately, all my characters I sent to string2Number are returned with 0. I can't get it running. Can someone point me in the right direction?
  • Hi,
    i think the problem is that you are comparing chars with strings.

    "1", is a string.
    strings have a function called toCharArray().
  • It seems to me that you are trying to convert each character in a given String to a Number. Is that correct? I think you could probably just fix this by using single quotes around each character...

    function string2Number(char) {
    if (char.equals('1')) { return 1;}
    if (char.equals('2')) { return 2;}
    if (char.equals('3')) { return 3;}
    if (char.equals('4')) { return 4;}
    ...
    if (char.equals('A')) {return 10;}
    return 0;
    }


    Of course that overlooks the fact that the code is probably doing way more than it needs to to get the functionality you want. I believe this will work just as well, will not require an implementation of string2Number(), and will likely be more efficient.

    var numberArray = new [ string.length() ];
    for (var i = 0; i < string.length(); ++i) {
    numberArray= string.substring(i, i+1).toNumberWithBase(16);
    }
    [/code]
  • Hi Travis,

    You are asking for the use case behind that code. We'll, I try to store a set of configurations (which is done via GC) in a string where each configuration setting is represented by one character. Therefore converting to hex would in some cases not be enough possibilities. If you have a setting list where the user can select each possible color for an item, 14 possibilities are already needed plus the possibility to not draw an item at all is 15. So it's just one left and then this hex method would not work.

    I will double check the code if it is fine to live with this limitation. Thanks for now. Bernd
  • You don't have to use base 16. The toNumberWithBase() supports bases up to 36 (0123...9ABC...XYZ). That should give you plenty of flexibility.

    Are you trying to avoid doing settings for a bunch of options or something?

    Travis