Friday, March 6, 2009

A handy little string function...

For the Caminalcule project I'm finding it easier to represent a genotype as a string because I can easily manipulate strings. But LSL is not real whippy on the string manipulation front.One function I needed was one that would substitute a sub-string starting at a certain position in an original string without making any other changes in the original string.

There are functions that do similar things but they rely on having a recognizable set of characters in the original string as in standard find and replace. But what I wanted was a function that goes to a particular position in the original string where I (or a script) specify where the position starts.

This is important for me because the way I represent genotypes there are some things that change a lot, but somethings may not change very often and yet I want to keep those things together with the more variable stuff-kind of like what happens in a chromosome.

So if I have two sentences:

"The sly big fox is learning scripting." and

"The big sly cat is learning scripting" ,

I might want to change what ever starts at letter 9 with the substring "red". Hence my little function:

replace_string(string original,string sub_string,integer pos).

Try copying the following code and inserting it in to a prim and let me know what you think. Given Blogger's tendency to mess up LSL code, you might have to change a few things by hand. Or IM me (Simone Gateaux) in world and I will send the script to you.

//begin code here
string replace_string(string original,string sub_string,integer pos)
//replaces part of string starting at pos with substring; does not change the original string length
//real handy for me

integer orig_length;
integer length;
string new_string;
length = llStringLength(sub_string);
orig_length = llStringLength(original);
if ((orig_length-1) > pos &&( pos >= 0))

new_string = llInsertString(original,pos,sub_string);
new_string = llDeleteSubString(new_string,pos+length, pos+length -1+length);

else new_string = original;
return new_string;

} //end function


touch_start(integer num_detected)
string newstring;
string oldstring = "The sly big fox is learning how to script.";
string replacement = "red";
integer position = 8; //position start at 0 index so here 8 is the start of "big"
newstring = replace_string(oldstring,replacement,position);
//end code

No comments: