Useful String Functions
Some functions for modifying and working with strings.
+=, @=
These two operators combine string concatenation and assignment. $=
doesn't work, that's why +=
is used here. (see [Scripting Operators])
static final operator string += (out string A, coerce string B) { A = A $ B; return A; }
static final operator string @= (out string A, coerce string B) { A = A @ B; return A; }
Lower
This function is the equivalent to Caps that converts all uppercase characters in a string to lowercase (while leaving non-alphabetical characters untouched).
static final function string Lower(coerce string Text) { local int IndexChar; for (IndexChar = 0; IndexChar < Len(Text); IndexChar++) if (Mid(Text, IndexChar, 1) >= "A" && Mid(Text, IndexChar, 1) <= "Z") Text = Left(Text, IndexChar) $ Chr(Asc(Mid(Text, IndexChar, 1)) + 32) $ Mid(Text, IndexChar + 1); return Text; }
IsUpper, IsLower
These functions detect whether a string is completely uppercase or lowercase.
static final function bool IsUpper(coerce string S) { return S == Caps(S); }
static final function bool IsLower(coerce string S) { return S == Lower(S); }
AlphaNumeric
This function leaves only alphanumerical characters in the string, i.e. A-Z and 0-9, and converts alphabetical characters to uppercase. Useful for sorting items by name.
static final function string AlphaNumeric(string s) { local string result; local int i, c; for (i = 0; i < Len(s); i++) { c = Asc(Right(s, Len(s) - i)); if ( c == Clamp(c, 48, 57) ) // 0-9 result = result $ Chr(c); else if ( c == Clamp(c, 65, 90) ) // A-Z result = result $ Chr(c); else if ( c == Clamp(c, 97, 122) ) // a-z result = result $ Chr(c - 32); // convert to uppercase } return result; }
LTrim, RTrim, Trim
These functions remove spaces from the left, the right or both sides of a string.
static final function string LTrim(coerce string S) { while (Left(S, 1) == " ") S = Right(S, Len(S) - 1); return S; }
static final function string RTrim(coerce string S) { while (Right(S, 1) == " ") S = Left(S, Len(S) - 1); return S; }
static final function string Trim(coerce string S) { return LTrim(RTrim(S)); }
ReplaceText
This function replaces any occurance of a substring Replace
inside a string Text
with the string With
. This is a modified version of the ReplaceText
function available in the UWindowWindow class which doesn't return the string but assigns it to the variable Text
.
static final function string ReplaceText(coerce string Text, coerce string Replace, coerce string With) { local int i; local string Output; i = InStr(Text, Replace); while (i != -1) { Output = Output $ Left(Text, i) $ With; Text = Mid(Text, i + Len(Replace)); i = InStr(Text, Replace); } Output = Output $ Text; return Output; }