Difference between revisions of "String Compare"

From Second Life Wiki
Jump to navigation Jump to search
 
Line 1: Line 1:
The following code returns 1, -1 or 0. The 1 and -1 are essentially random, however it will return the same value every time the script is executed. 0 Is returned when, and only when, the strings are exactly equal.
The following code returns 1, -1 or 0. The 1 and -1 are essentially random, however it will return the same value every time the script is executed. 0 Is returned when, and only when, the strings are exactly equal.


I have used this script for comparing the [[Key|Key's]] of two objects in a dynamic set of sensors, to decide which one should be the "Master" in the region to tell me information. I'm sure there can be more uses to this...


If someone could please optimize the script, as it is currently very inefficient.
<pre>
integer compare(string s1, string s2) {
integer compare(string s1, string s2) {
     if (s1 == s2) {
     if (s1 == s2) {
Line 36: Line 40:
     return 0;
     return 0;
}
}
</pre>

Revision as of 17:32, 25 May 2007

The following code returns 1, -1 or 0. The 1 and -1 are essentially random, however it will return the same value every time the script is executed. 0 Is returned when, and only when, the strings are exactly equal.

I have used this script for comparing the Key's of two objects in a dynamic set of sensors, to decide which one should be the "Master" in the region to tell me information. I'm sure there can be more uses to this...

If someone could please optimize the script, as it is currently very inefficient.

integer compare(string s1, string s2) {
    if (s1 == s2) {
        return 0;
    } else if (llStringLength(s1) < llStringLength(s2)) {
        return 1;
    } else if (llStringLength(s1) > llStringLength(s2)) {
        return -1;
    } else {
        if (llStringLength(s1) > 32) {
            s1 = llMD5String(s1, 0);
            s2 = llMD5String(s2, 0);
        }
        integer i = 0;
        list l1 = llParseString2List(s1, [""], []);
        list l2 = llParseString2List(s2, [""], []);
        s1 = llStringToBase64(s1);
        s2 = llStringToBase64(s2);
        string com = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm=+";
        integer a;
        integer b;
        while (i < llStringLength(s1)) {
            a = llSubStringIndex(com, llList2String(l1, i));
            b = llSubStringIndex(com, llList2String(l2, i));
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            }
            
            i++;
        }
    }
    return 0;
}