Forum Post
Index > Scripting > String Handling

Author/Date String Handling
fret
11/03/2007 10:03pm
There are a number built in functions for handling strings. First to find a character in a string use:
int Strchr(string, char[, string_length]);

Which returns a zero based index of 'char' found in 'string' or -1 if not found. The 'string_length' parameter is option. If supplied only the first 'string_length' characters are searched.
s = "Some string";
i = Strchr(s, "r");

Would set 'i' to 7. All the string functions should be utf-8 safe and operate on characters. So 7 means the 8th character, not the 8th byte and 0 would mean the 1st character.

To find a string use:
int Strstr(string1, string2[, case_insensitive[, string_length]]);

Finds 'string2' inside 'string1' and returns the index of the first match, or -1 if a match is not found. Specify 'case_insensitive' to set the sensitivity, or it defaults to true. 'string_length' sets the maximum characters to search, otherwise the whole of 'string1' is search.

To compare a string against another use:
int Strcmp(string1, string2[, case_insensitive[, string_length]]);

Compares 'string1' against 'string2' in the same way as the C function strcmp. Optionally specify 'case_insensitive' to set case sensitivity, or it defaults to true.

To copy out part of a string use:
String Substr(string, start[, length]);

This returns part of a string as a new variable, 'start' is the start character of the part to copy, and 'length' is the number of characters from that start point to copy, if not supplied it'll copy to the end of 'string'.

Of course you can also access characters within the string using array dereferencing:
s = "Some string";
s[3] = "k";
Reply