stristr

From Second Life Wiki
Revision as of 16:21, 30 May 2010 by Ugleh Ulrik (talk | contribs) (Created page with '{{LSL_Function |func=Stristr |mode=user |p1_type=string|p1_name=haystack|p1_desc=The input string |p2_type=string|p2_name=needle|p2_desc=the search within |p3_type=integer|p3_nam...')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Summary

Function: string Stristr( string haystack, string needle, integer before_needle );

Returns part of haystack string from the first occurrence of needle to the end of haystack.
Returns a string from the first occurrence of needle to the end of haystack.

• string haystack The input string
• string needle the search within
• integer before_needle If TRUE, Stristr returns the part of the haystack before the first occurrence of the needle, else after first occurrence.

This function can also be used to determine if a line is in a string, If needle is not found it will return with a null string for if else statements.

Specification

<lsl> //Function created by Ugleh Ulrik string stristr(string haystack, string needle, integer before_needle){

       integer msl = llStringLength(haystack);
       integer mi;
       list mlist;
       do//we make a list out of the message to use ListFindList
       mlist += [llGetSubString(haystack, mi, mi)];
       while(msl>++mi);
       integer ssl = llStringLength(needle);
       integer si;
       list slist;
       do//we make a list out of the search to use ListFindList
       slist += [llGetSubString(needle, si, si)];
       while(ssl>++si);
       if (llListFindList(mlist,slist) == -1)//-1 means not found, so we return it as null
       return "";
       if(before_needle)
       return llGetSubString(haystack, msl, ((integer)llListFindList(mlist,slist) - 1));
       return llGetSubString(haystack, ((integer)llListFindList(mlist,slist) + ssl), msl);
       

} </lsl>

Examples

This example uses its basic feature, to provide the content left, or right of the searched string. <lsl> default {

   touch_start(integer total_number)
   {
       string source = "Hello there, Ugleh is my name!";
        string mess = stristr(source,"Ugleh",FALSE); //False means after Needle
        llOwnerSay(mess);//outputs  "  is my name!"
        
        mess = stristr(source,"Ugleh",TRUE); //True means before Needle.
        llOwnerSay(mess);//outputs "Hello there, "
        
   }

}

</lsl>

This uses the function to provide an if else statement <lsl> default {

   touch_start(integer total_number)
   {
       string source = "Ugleh was here";//change to "Strife was here" to get a different result
        string mess = stristr(source,"Ugleh",FALSE);
        llOwnerSay(mess);//outputs  "  is my name!"
        
        mess = stristr(source,"Strife",TRUE);
        if(mess)
        llSay(0, "Looks like Strife was here");
        else
        llSay(0, "Looks like Ugleh was here");
        
        
   }

}

</lsl>