Today I found that C# does not have a built in method for trimming strings using another string. The built in method for trimming strings does not take a string, but only a char. However I was in need of trimming the string using a specific sequence of chars. Here is what I have used:
public string Trim(string toBeTrimmed, string trimString){
if (toBeTrimmed == null || trimString == null)
return toBeTrimmed;
while (toBeTrimmed.StartsWith(trimString))
{
toBeTrimmed = toBeTrimmed.Substring(trimString.Length);
}
return toBeTrimmed;
}
The above loops over the string and substrings it, until it no longer starts with the given string. The following is how it is invoked:
var trimmedString = Trim("abcabccbaabcTestTest", "abc");
Console.WriteLine("Result:" + trimmedString);
// Output = Result:cbaabcTestTest
I hope this helps someone out there, let me know below if it did!