2

I am trying to iterate over an array of strings and check/replace if any of the strings exist in the input string. Using LINQ, this is what i have so far.

string input = "/main/dev.website.com"
string[] itemsToIgnore = { "dev.", "qa.", "/main/" };
string website = itemsToIgnore
                    .Select(x => 
                           { x = input.Replace(x, ""); return x; })
                    .FirstOrDefault();

When i run this, nothing actually happens and my input string stays the same?

1

1 Answer 1

5
string website = itemsToIgnore
                   .Aggregate(input, (current, s) => 
                         current.StartsWith(s) ? current.Replace(s, string.Empty) : current);

and without Linq

foreach (var part in itemsToIgnore) 
{
  if (website.StartsWith(part))
  {
    website = website.Replace(part, string.Empty);
  }
}
Sign up to request clarification or add additional context in comments.

10 Comments

How can i avoid with Replace matching on something like "should.", i only ever want to replace if i get an exact match with nothing in front.
May you explain your wish with some example?
If i have the string "should." noticed the "." after the word "should", and my itemsToIgnore list looks for "d.", it will catch replace the string "should." as "shoul". I only want to replace with an empty string if there is nothing in front of the itemsToIgnore list
I have made changes in answer for this case
So that fixed my problem but raises another issue. If my itemsToIgnore list equals {"d.", "red."}, and my input is "d.something.com", the StartsWith command returns false and doesn't replace it. Why is it ignoring my first item ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.