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 of the program ===
Darth Vader is scary.
Darth Vader is not scary.
=== Example 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 of the program ===
Dot Net Perls is about Dot Net.
Dot Basket Perls is about Dot Basket.
Using 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.
=== Example program that uses StringBuilder === 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 of the program === This is an example. Here is an example. Sentence: Here is an example.
Rewriting 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 === /// <summary> /// A - Eliminates extra whitespace. /// </summary> 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 === /// <summary> /// B - Eliminates extra whitespace. /// </summary> 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(); }
'.net' 카테고리의 다른 글
Microsoft.Jet.OLEDB.4.0 를 이용한 Excel 파일 읽기시 주의사항 (1) | 2010.07.09 |
---|---|
문자열 다루기 (0) | 2010.05.26 |
Microsoft MSDN 무료 기술 서적 (0) | 2010.05.24 |
페이지내 컨트롤 데이터를 QueryString으로 가져오는 코드 (0) | 2010.05.20 |
Server.UrlEncode와 HttpUtility.UrlEncode의 차이점이 관해 (0) | 2010.02.24 |