Jump to content
Sign in to follow this  
mind

fnc_replaceStringDeep. This is not help asking topic. Just small function for share.

Recommended Posts

Hi all,

 

Have not found a function to change every occurrence of given string in deeply nested array to another string, so made it myself.

Hopefully some one will find it usefull  ;)

Fill free to critic and/or improve, this way everyone wins  :)

 

fnc_replaceStringDeep = {
	private ["_arr","_search","_replace","_count","_scanArray"];
	_arr = param [0, [], [[]]];
	_search = param [1, "", [""]];
	_replace = param [2, "", [""]];
	if (count _arr == 0) exitWith {0};
	if (_search == "") exitWith {-1};
	if (_replace == "") exitWith {-1};
	_count = 0;
	_scanArray = {
		{
			if (typeName _x == "STRING") then {
				if (_x isEqualTo _search) then {
					_this set [_forEachIndex, _replace];
					_count = _count + 1;
				};
			};
			if (typeName _x == "ARRAY") then {
				_x call _scanArray;
			};
		} forEach _this;
	};
	_arr call _scanArray;
	_count;
};

 

Code will return positive number showing how many times string was replaced, zero if string was not found and -1 if input is wrong.

This function WILL modify provided array, if this is not wanted, perform function with copy of array.

Function will make CaSE SenSitivE check.

 

Use showcase:

myArray = ["BAD","fsgg",0,[0,5,3,"BAD"],"something",[[0,0,5,4,"BAD",["Bad"]]],["ddftest","BAD"],[],[]];
searchString = "BAD";
replaceString = "GOOD";

result = [myArray, searchString, replaceString] call fnc_replaceStringDeep;

So here is output

result == 4

myArray == ["GOOD","fsgg",0,[0,5,3,"GOOD"],"something",[[0,0,5,4,"GOOD",["Bad"]]],["ddftest","GOOD"],[],[]]
  • Like 1

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
Sign in to follow this  

×