Posted on May 12, 2018 at 13:24 (GMT +00:00) by
Colin
Back again with another function that is useful, string replacement!
This one is quite obvious, you want to replace some substrings of a string with your replacement.... but how would you do that in SQF when Arma does not have any pre-defined functions or exposed c functions available for string replacement.....
//
// PX_fnc_stringReplace :: Replace substrings
// Author: Colin J.D. Stewart
// Usage: ["abc1ghi", "1", "def"] call PX_fnc_stringReplace;
//
PX_fnc_stringReplace = {
params["_str", "_find", "_replace"];
private _return = "";
private _len = count _find;
private _pos = _str find _find;
while {(_pos != -1) && (count _str > 0)} do {
_return = _return + (_str select [0, _pos]) + _replace;
_str = (_str select [_pos+_len]);
_pos = _str find _find;
};
_return + _str;
};
This function will do just that, it is very easy to use.
["xxx is awesome, I love xxx!", "xxx", "Arma"] call PX_fnc_stringReplace;
// Output: Arma is awesome, I love Arma!
Keep checking back for more!
EDIT:
A small update to allow passing optional multiple find strings via array.
//
// PX_fnc_stringReplace :: Replace substrings
// Author: Colin J.D. Stewart
// Usage: ["xxx is awesome, I love xxx!", "xxx" || [], "Arma"] call PX_fnc_stringReplace;
//
PX_fnc_stringReplace = {
params["_str", "_find", "_replace"];
private["_return", "_len", "_pos"];
if (!(_find isEqualType [])) then {
_find = [_find];
};
{
_return = "";
_len = count _x;
_pos = _str find _x;
while {(_pos != -1) && (count _str > 0)} do {
_return = _return + (_str select [0, _pos]) + _replace;
_str = (_str select [_pos+_len]);
_pos = _str find _x;
};
_str = _return + _str;
} forEach _find;
_str;
};
e.g.
["xxx is awesome, I love yyy!", ["xxx", "yyy"], "Arma"] call PX_fnc_stringReplace;
// Output: Arma is awesome, I love Arma!