1

Whats is correct to do?

check if exists, then remove?

var input = "foo #main baa"; 
if(input.Contains("#main")) {
   input = input.Replace("#main", "");
}

or just:

input = input.Replace("#main", "");

Well, this seem a simple question,but I really want know. Thanks in advance.

5 Answers 5

4

The Contains check actually just makes your code slower.
Remove it.

The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.

Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.

Sign up to request clarification or add additional context in comments.

Comments

4

Just do the replacement - if it's not there, nothing should happen.

Comments

1

Just make the call to Replace(). If the substring isn't found nothing happens and you avoid an additional call to Contains().

Comments

0

I would do this:

input = input.Replace("#main", "").Replace("  "," ");

To remove any double spaces.

Comments

0

Just remove it. The only thing to check is if the string is null or not.

Comments

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.