Game Development Community

String Replace Function

by Ben Versaw · in Torque Game Engine · 02/18/2006 (11:52 pm) · 1 replies

I found a need for a string replace type function and couldn't find anything like that (if I miss something please point it out) so I created my own.

function str_replace(%toReplace,%replaceWith,%replaceIn)
{
	for(%i=0;%i<strLen(%replaceIn);%i++)
	{
		if(getSubStr(%replaceIn,%i,strLen(%toReplace)) $= %toReplace)
		{
			%before = getSubStr(%replaceIn, 0, %i); //Get stuff before
			%after = getSubStr(%replaceIn, %i+strLen(%toReplace), strLen(%replaceIn)-(%i+strLen(%toReplace)));
			%newstring = %before @ %replaceWith @ %after;
			return %newstring;
		}
	}
}

#1
02/19/2006 (3:50 am)
There is already one (:

%test = "test-123-k";
%test = strreplace(%test, "123", "321");
echo(%test);

This will echo out: "test-321-k".