The Mask
The Mask

Reputation: 17427

about string removing in C#

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.

Upvotes: 1

Views: 237

Answers (5)

SLaks
SLaks

Reputation: 887443

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.

Upvotes: 4

lontivero
lontivero

Reputation: 5275

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

Upvotes: 0

Hogan
Hogan

Reputation: 70523

I would do this:

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

To remove any double spaces.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124642

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

Upvotes: 1

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19349

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

Upvotes: 4

Related Questions