C # is the best way to do this?

Hi, I have this code below and I'm looking for a nicer / faster way to do this.

Thank!

string value = "HelloGoodByeSeeYouLater";
string[] y = new string[]{"Hello", "You"};

foreach(string x in y)
{
    value = value.Replace(x, "");
}
+3
source share
5 answers

You can do:

y.ToList().ForEach(x => value = value.Replace(x, ""));

Although I think your option is more readable.

+4
source

Forgive me, but someone has to say it,

value = Regex.Replace( value, string.Join("|", y.Select(Regex.Escape)), "" );

Perhaps faster since it creates fewer lines.

EDIT : credit for Gabe and lasseespeholt for Escape and Select.

+3
source

, .

LINQ:

value = y.Aggregate(value, (acc, x) => acc.Replace(x, ""));

String:

value = String.Join("", value.Split(y, StringSplitOptions.None));

, , foreach.

+2

, . foreach , , . .

. Linq , ; , , , . Regex, .

, , . OP, , - .

№1 .

№2 .

# 1

# char , . :

  • Peeks
  • ,

, , . .

HTML DOM-. , STYLE ( ) , STYLE.

, , ( / , ).

, .Net , ( ).

# 2

, . , , , . , . , , , , , .

, .

(< 1ms) , , , FAA .. 13K, 300K ( , , ).

, , , Sky Harbor KPHX. :

KPH KPHX

Ph Pho Phoe

Ari

Sk Sky

Ha Har

, , , , . , , .

, .

+2

(, "" )

, , .

value = value.Remove(y);
// or
value = value.Remove("Hello", "You");
// effectively
string value = "HelloGoodByeSeeYouLater".Remove("Hello", "You");

.

Implementation of the extension method:
I am going to complete your own implementation (shown in your question) in the extension method for pretty or elegant points, and also use params to provide some flexibility in passing arguments. You can replace someone with an even faster implementation body with this method.

static class EXTENSIONS {
    static public string Remove(this string thisString, params string[] arrItems) {
       // Whatever implementation you like:
       if (thisString == null)
           return null;
       var temp = thisString;
       foreach(string x in arrItems)
            temp = temp.Replace(x, "");
       return temp;
    }
}

This is the brightest idea that I can come up with right now, when no one else has touched.

+1
source

Source: https://habr.com/ru/post/1767634/


All Articles