الأربعاء، 17 ديسمبر 2008

Strings and String Builders


Strings and String Builders

ü System.String provides a set of members for working with text.

ü They also provide the means to manipulate that data through their members.

string s = "this is some text to search";

s = s.Replace ("search", "replace");

Console.WriteLine(s);

Note

We determine any word we want to replace from the text and method match the word you want to replace and replace it with the new word.

ü Strings of type System.String are immutable (ثابت) in .NET and also in java. That means any change to a string causes the runtime to create a new string and abandon (يتخلى عن) the old one. That happens invisibly, and many programmers might be surprised to learn that the following code allocates four new strings in memory:

string str;

str = "Ahmed"; // "Ahmed"

str += "Rabie"; // "Ahmed Rabie"

str += "Ahmed"; // "Ahmed Rabie Ahmed"

str += "El Bohoty"; // "Ahmed Rabie Ahmed El Bohoty"

Console.WriteLine(str);


Note

Only the last string has a reference; the other three will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance. There are several ways to avoid temporary strings:

Use the String class’s Concat, Join, or Format methods to join multiple items in a single statement.

Use the StringBuilder class to create dynamic (mutable) strings.

The StringBuilder solution is the most flexible because it can span multiple statements. The default constructor creates a buffer 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like. The following code demonstrates using StringBuilder:

System.Text.StringBuilder sb = new System.Text.StringBuilder (30);

sb.Append ("Ahmed"); // Build string.

sb.Append("Rabie");

sb.Append("Ahmed");

sb.Append("El Bohoty");

string s = sb.ToString(); // Copy result to string.

Console.WriteLine(s);

0 التعليقات: