.NET: Trim a String With String Values Instead of char Values

4/29/2015 8:39:36 PM

.NET allows you to easily trim whitespace characters to trim the start and end of a string or to trim based on an array of char's (char[]). It does not provide a way to do this with an array of strings. Below is code to do that.

public static string Trim(string initialValue, string valueToTrim)
{
	return Trim(initialValue, new string[] { valueToTrim });
}
public static string Trim(string initialValue, string[] valuesToTrim)
{
	if (initialValue == null)
	{
		return initialValue;
	}

	//start
	foreach (var valueToTrim in valuesToTrim)
	{
		while (initialValue.StartsWith(valueToTrim))
		{
			//if lenght is 1, start at 1 to remove position at 0
			initialValue = initialValue.Substring(valueToTrim.Length);
		}
	}

	//end
	foreach (var valueToTrim in valuesToTrim)
	{
		while (initialValue.EndsWith(valueToTrim))
		{
			//include everything but the last  = to the length of current value to trim
			initialValue = initialValue.Substring(0, initialValue.Length - valueToTrim.Length);
		}
	}

	return initialValue;
}