Chủ Nhật, 25 tháng 9, 2011

C# Replace String Examples

You want to replace one substring in a string with another in your C# program. You may need to swap specific characters with other characters or words. Also, see if you can optimize string replacements with StringBuilder. This page has some Replace method examples, and also a real-world example of using StringBuilder Replace, using the C# programming language.
Key points: Replace is an instance method on String. It replaces all instances of the specified string. It returns a copied string. The original string is not changed.

 

Example 1

Here we see a very simple example of using the string Replace method. Note that you must assign the result of the string Replace method to a new variable. Other Replace methods in the base class library may not require this.
Program that uses Replace [C#]

using System;

class Program
{
    static void Main()
    {
	const string s = "Darth Vader is scary.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result of Replace to a new string.
	string v = s.Replace("scary", "not scary");
	Console.WriteLine(v);
    }
}

Output

Darth Vader is scary.
Darth Vader is not scary.

Every instance

Here we note that the Replace methods replace every instance of the specified substring. To demonstrate, the next console program replaces the word "Net" with the word "Basket". Don't call Replace two times in the example. The second Replace will not do anything and will result in needless CPU cycles being used.
Program that uses Replace [C#]

using System;

class Program
{
    static void Main()
    {
	const string s = "Dot Net Perls is about Dot Net.";
	Console.WriteLine(s);

	// Note:
	// You must assign the result to a new variable.
	// Every instance is replaced.
	string v = s.Replace("Net", "Basket");
	Console.WriteLine(v);
    }
}

Output

Dot Net Perls is about Dot Net.
Dot Basket Perls is about Dot Basket.

StringBuilder Replace

Here we see the basics of StringBuilder and its Replace and Insert methods. With StringBuilder, Replace works the same way as with strings but it doesn't need its result to be assigned.
Program that uses StringBuilder [C#]

using System;
using System.Text;

class Program
{
    static void Main()
    {
	const string s = "This is an example.";

	// A
	// Create new StringBuilder from string
	StringBuilder b = new StringBuilder(s);
	Console.WriteLine(b);

	// B
	// Replace the first word
	// The result doesn't need assignment
	b.Replace("This", "Here");
	Console.WriteLine(b);

	// C
	// Insert the string at the beginning
	b.Insert(0, "Sentence: ");
	Console.WriteLine(b);
    }
}

Output

This is an example.
Here is an example.
Sentence: Here is an example.
Explanation. The example console program uses a StringBuilder containing a short sentence. In part A, it creates the new StringBuilder and prints it to the screen.
Next two parts. In part B, it replaces the word "This" with the word "Here". The resulting string it prints will have the new word where the old word was. In part C, we see a similar method, the Insert method. It is like a Replace call where an empty character is replaced.
StringBuilder SecretsProgramming tip.

Problem with Replace

The biggest problem with Replace is that it creates more string copies each time it is called. This can often lead to measurable performance problems in large projects. Microsoft notes that "This method does not modify the value of the current instance. Instead, it returns a new string in which all occurrences of oldValue are replaced by newValue."
msdn.microsoft.com

Rewrite with StringBuilder

Fortunately, it is usually easy to rewrite your wasteful string Replace code with StringBuilder Replace. For the example, I show the original code that uses string and then the new StringBuilder code.
String Replace example [C#]

/// 
/// A - Eliminates extra whitespace.
/// 
static string MinifyA(string p)
{
    p = p.Replace("  ", string.Empty);
    p = p.Replace(Environment.NewLine, string.Empty);
    p = p.Replace("\\t", string.Empty);
    p = p.Replace(" {", "{");
    p = p.Replace(" :", ":");
    p = p.Replace(": ", ":");
    p = p.Replace(", ", ",");
    p = p.Replace("; ", ";");
    p = p.Replace(";}", "}");
    return p;
}

StringBuilder Replace example [C#]

/// 
/// B - Eliminates extra whitespace.
/// 
static string MinifyB(string p)
{
    StringBuilder b = new StringBuilder(p);
    b.Replace("  ", string.Empty);
    b.Replace(Environment.NewLine, string.Empty);
    b.Replace("\\t", string.Empty);
    b.Replace(" {", "{");
    b.Replace(" :", ":");
    b.Replace(": ", ":");
    b.Replace(", ", ",");
    b.Replace("; ", ";");
    b.Replace(";}", "}");
    return b.ToString();
}
Notes. It ends up creating lots of string copies. It uses string constants such as Environment.NewLine and string.Empty. It replaces whitespace around punctuation. It can be used to strip whitespace from CSS files.
Environment.NewLine string.Empty ExampleNotes on StringBuilder method. It instantiates a new StringBuilder from the parameter string. It does the same replacements as Method A. The return value of Replace doesn't need to be assigned.

Benchmarks

QuestionHere we want to see if there is a difference between Method A, which uses string Replace, and Method B, which uses StringBuilder Replace. It is great to read MSDN and know the two are different—but is the timing different significant?
Replace methods benchmark for short strings
    20 characters in strings; 10000 iterations.

Method A - String Replace:         5.60 seconds
Method B - StringBuilder Replace:  0.62 seconds [faster]

Replace methods benchmark for long strings
    1000 characters in strings; 10000 iterations.

Method A - String Replace:        21.80 seconds
Method B - StringBuilder Replace   4.89 seconds [faster]
Experiment results. I found that string Replace took considerably more time in this case. This is because of the repeated string copying due to the semantics of string Replace, versus StringBuilder which modifies buffers in-place.
Conclusion from the results. Clearly, avoiding string Replace in situations where more than one replacement is required is a good guideline. Note that there may be cases where string Replace can perform better, even on more than one Replace.

Performance

Some forms of the Replace method are faster than others. For example, using char arguments is faster than string arguments. Also, the Replace method is faster if no changes are made to the underlying string.
Replace PerformanceSplit strings.

Split

In this part, we note that you can use Replace on a string you want to split to filter out escaped characters that would otherwise cause incorrect results. You can do this by replacing the characters before calling Split, and then restoring them.
Split Escape Characters

Replace whitespace

Here, we mention that you often will need to remove or change whitespace in strings, particularly those read in from files. There is now a complete guide to replacing or converting whitespace—such as tabs, spaces, and line breaks—on this site.
Whitespace Tips

Summary

In this article, we saw some interesting examples and learned about the behavior of two Replace methods, as well as Insert, in the C# language. String Replace is very different than StringBuilder Replace, although on the surface they are the same. StringBuilder is purely an optimization, but considering the prevalence of string usage, it is critical to use.
String Type
copyright: http://www.dotnetperls.com/replace

1 nhận xét:

  1. I get been deceased such a long sentence from Blogging macrocosm bothers me.
    I talk for myself because Scott, around blogging in bed.
    I got some new Risible ideas with you all. If we are truly to puzzle out the problem of gun what seemed
    to be a veiled allusion to the s Amendment correct to deliver blazonry, I consider in the
    Organization, too.

    Here is my web-site click here

    Trả lờiXóa

Hãy để lại tin nhắn của bạn nhé. Mình luôn muốn nghe ý kiến của bạn. Cám ơn bạn đã ghé thăm blog nha. See you