Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string if a string ends with a specific word

Tags:

c#

.net

I need to trim strings if there is a word where coming at the end of string. What is the fast performing approach in C# for this?

Note: The word to trim can be anything.. WHERE is just an example

string text1 = "My hosue where sun shines";  //RESULT: "My hosue where sun shines"
string text2 = "My where"; //RESULT: "My"
string text3 = "My where I WHERE"; //RESULT:"My where I"
like image 573
LCJ Avatar asked Sep 05 '25 03:09

LCJ


1 Answers

you can use string.EndsWith method and string.Substring

public static string Trim(this string s, string trimmer)
{

    if (String.IsNullOrEmpty(s)|| String.IsNullOrEmpty(trimmer) ||!s.EndsWith(trimmer,StringComparison.OrdinalIgnoreCase))
        return s;
    else
        return s.Substring(0, s.Length - trimmer.Length);
}
like image 139
Damith Avatar answered Sep 07 '25 19:09

Damith