Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim a string from a string

Tags:

string

c#

trim

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!

like image 330
imsocontigo Avatar asked Oct 31 '25 21:10

imsocontigo


1 Answers

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);
like image 84
Udi Y Avatar answered Nov 03 '25 09:11

Udi Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!