05.05.2012, 15:17
strreplace - Replace occurrences of the search string with the replacement string.
You can see a demo & test the function here.
Examples:
You can see a demo & test the function here.
pawn Код:
/*
* strreplace - Replace occurrences of the search string with the replacement string.
*
* Supports both packed and unpacked strings.
*
* Parameters:
* string[] - The string to perform the replacing in.
* search[] - The string to look for.
* replacement[] - The string to put instead of "search".
* ignorecase - Whether the search for "search" should be case-insensitive. Defaults to false.
* pos - The position to start at. Defaults to 0 (the beginning).
* limit - Limit the number of replacements. Defaults to -1 (no limit).
* maxlength - The size of "string". Defaults to sizeof(string), which almost always is what you want.
*
* Returns:
* The number of replacements that were made.
*/
stock strreplace(string[], const search[], const replacement[], bool:ignorecase = false, pos = 0, limit = -1, maxlength = sizeof(string)) {
// No need to do anything if the limit is 0.
if (limit == 0)
return 0;
new
sublen = strlen(search),
replen = strlen(replacement),
bool:packed = ispacked(string),
maxlen = maxlength,
len = strlen(string),
count = 0
;
// "maxlen" holds the max string length (not to be confused with "maxlength", which holds the max. array size).
// Since packed strings hold 4 characters per array slot, we multiply "maxlen" by 4.
if (packed)
maxlen *= 4;
// If the length of the substring is 0, we have nothing to look for..
if (!sublen)
return 0;
// In this line we both assign the return value from "strfind" to "pos" then check if it's -1.
while (-1 != (pos = strfind(string, search, ignorecase, pos))) {
// Delete the string we found
strdel(string, pos, pos + sublen);
len -= sublen;
// If there's anything to put as replacement, insert it. Make sure there's enough room first.
if (replen && len + replen < maxlen) {
strins(string, replacement, pos, maxlength);
pos += replen;
len += replen;
}
// Is there a limit of number of replacements, if so, did we break it?
if (limit != -1 && ++count >= limit)
break;
}
return count;
}
pawn Код:
new string[200];
// Simple replacement
string = "You can't compare apples and oranges.";
strreplace(string, "apples", "oranges");
print(string);
// Case-insensitive replace
string = "LoremLoremLoremLorem ipsum dolor sit amet, consectetur adipiscing elit.";
strreplace(string, "lorem", "LOREM", .ignorecase = true);
strreplace(string, "DOLOR", "dooloor", .ignorecase = true);
print(string);
// Using an empty replacement string
string = "1111122222333334444455555";
strreplace(string, "2", "");
print(string);
// Using the "limit" argument
string = "bbbbbbbbbb";
strreplace(string, "b", "a", .limit = 5);
print(string);
// Using the "pos" argument
string = "---bbbbbbbbbb---";
strreplace(string, "b", "a", .pos = 5);
print(string);