0

So the normal way to trim something from a string is by trimming it by the character.

For example:

string test = "Random Text";
string trimmedString = test.Trim(new Char[] { 'R', 'a', 'n'});
Console.WriteLine(trimmedString);
//the output would be "dom Text"

But instead of doing this, is there a way to just completely remove the combined characters "Ran" from the string?

For example:

string test = "Random Text";
string trimmedString = test.Trim(string "Ran");
Console.WriteLine(trimmedString);
//the output would be "dom Text"

Now, the code above gives an error, but was wondering if something like this is possible, thank you!

Yong Shun
  • 35,286
  • 4
  • 24
  • 46

3 Answers3

1

You can use Remove like this:

string test = "Random Text";
string textToTrim = "Ran";

if (test.StartsWith(textToTrim))
    test = test.Remove(0, textToTrim.Length);
if (test.EndsWith(textToTrim))
    test = test.Remove(test.Length - textToTrim.Length);
Udi Y
  • 258
  • 3
  • 12
0

You can convert the string to an array of chars, like this:

string trimmedString = test.Trim("Ran".ToArray());

However note that, trimming that way will not take care of the exact match (by order of the characters), so if your test is "aRndom Text", it will still be trimmed to just "dom Text".

If you want to trim the string by exact matching, you can use some code like this:

public static class TrimStringExtensions {
    public static string Trim(this string s, string toBeTrimmed){
         if(string.IsNullOrEmpty(toBeTrimmed)) return s;
         if(s.StartsWith(toBeTrimmed)){
              s = s.Substring(toBeTrimmed.Length);
         }
         if(s.EndsWith(toBeTrimmed)){
              s = s.Substring(0,s.Length - toBeTrimmed.Length);
         }
         return s;
    }
}

You can also use Regex for this:

public static class TrimStringExtensions {
     public static string Trim(this string s, string toBeTrimmed){
          if(string.IsNullOrEmpty(toBeTrimmed)) return s;
          var literal = Regex.Escape(toBeTrimmed);
          return Regex.Replace(s, $"^{literal}|{literal}$", "");
     }
}

Use it:

string trimmedString = test.Trim("Ran");
King King
  • 61,710
  • 16
  • 105
  • 130
0

I can see several ways of doing it depending on your needs.

A. What you do, but tiny bit smarter

string trimmedString = test.Trim("Ran".ToArray()); //Or TrimStart or TrimEnd

B. Replace

string trimmedString = test.Replace("Ran", "");

This would remove "Ran" anywhere in the string.

C. Replace only first occurrence

Please see C# - Simplest way to remove first occurrence of a substring from another string.

D. Regular expression

Please see Remove a leading string using regular expression

tymtam
  • 31,798
  • 8
  • 86
  • 126