Friday, May 14, 2010

The StringBuilder Class



The StringBuilder class is provided in the System.Text namespace to create an object that can hold a string value that can be changed. An object created with the StringBuilder class operates similarly to a string. The difference is that methods of a StringBuilder can directly manipulate the value stored. The methods and properties for a StringBuilder object are listed in table given below.
Table :The StringBuilder Methods and Properties
Methods or Properties                        Description
Append:                                 Appends an object to the end of the current StringBuilder.
AppendFormat:                    Inserts objects into a string base on formatting specifiers.
Capacity:                                Sets or gets the number of characters that can be held. Capacity can be increased up to the value of MaxCapacity.
Chars:                                     Sets or gets the character at a given index position using indexer notation.
EnsureCapacity:                    Ensures that the capacity of StringBuilder is at least as big as a provided
Value:                                     If the value is passed to EnsureCapacity, the value of the Capacity property is set to this new value. If MaxCapacity is less than the value passed, an exception is thrown.
Equals:                                   Determines whether the current StringBuilder is equal to the value passed.
Insert:                                    Places an object into StringBuilder at a given location.
Length:                                   Sets or gets the length of the current value stored in StringBuilder. Length cannot be larger than the Capacity of StringBuilder. If the current value is shorter than Length, the value is truncated.
MaxCapacity:                        Gets the maximum capacity for StringBuilder.
Remove:                                 Removes a specified number of characters, starting at a specified location within the current StringBuilder object.
Replace:                                 Changes all copies of a given character with a new character.
ToString:                               Converts StringBuilder to String.


The StringBuilder class can be used like other classes. The following program uses the StringBuilder object and several of the methods and properties presented in above table. This program has a user enter first, last, and middle names. The values are combined into a StringBuilder object.

The StringBuilder class is used to represent mutable strings. It starts at a predefined size (16 characters by default) and grows dynamically as more string data is added. It can either grow unbounded or up to a configurable maximum. For example:
=== Program that uses Replace () and Append () ===
using System;
using System.Text;

class Program
{
    static void Main()
    {
        StringBuilder builder = new StringBuilder("This is an example string");
        builder.Replace("an", "the"); // Replaces 'an' with 'the'.
        Console.WriteLine(builder);
        builder.Append(" that is an example.");
        Console.WriteLine(builder);
        
    }
}

=== Output of the program ===
This is the example string
This is the example string that is an example

=== Program that uses AppendFormat () ===
using System;
using System.Text;

class Program
{
    static int[] sb = new int[]{1,4,6};
   
    static void Main()
    {
        StringBuilder b = new StringBuilder();
        foreach (int i in sb)
        {
            b.AppendFormat("int: {0:0.0}\n",i);
        }
        Console.WriteLine(b.ToString());
    }
}
 

=== Output of the program ===

int: 1.0
int: 4.0
int: 6.0


=== using Remove () ===

 StringBuilder st = new StringBuilder("Football");
 st.Remove(4, 4);//Remove(int StartIndex,int length).
 Console.WriteLine(st);//Foot

=== using Insert () ===

StringBuilder st = new StringBuilder("Foot");
st.Insert(4, "ball");
Console.WriteLine(st);//Football

=== using Equals () ===
StringBuilder sb = new StringBuilder("c#");
StringBuilder sb1 = new StringBuilder("c#");
bool b= sb.Equals(sb1);
Console.WriteLine(b);//True

The chief advantage of a StringBuilder object over a string object is that it preallocates a default initial amount of memory in an internal buffer in which a string value can expand and contract. When that memory is used, however, .NET must allocate new memory for this internal buffer. You can reduce the frequency with which this occurs by explicitly defining the size of the new memory using either of two techniques. The first approach is to set this value when the StringBuilder class constructor is called. For example, the code:
        StringBuilder sb = new StringBuilder(200);

specifies that a StringBuilder object can hold 200 characters before new memory must be allocated.
The second approach is to change the value after the StringBuilder object has been created, using one of the following properties or methods of the StringBuilder object:
        sb.Capacity = 200;
        sb.EnsureCapacity(200);

Friday, May 7, 2010

OPERATOR OVERLOADING



 All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#. The following table shows the operators and their overloadability in C#.
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, –, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
&&, || They can’t be overloaded
() (Conversion operator) They can’t be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.
=, . , ?:, ->, new, is, as, size of These operators can’t be overloaded
In C#, a special function called operator function is used for overloading purpose. These special function or method must be public and static. They can take only value arguments.The ref and out parameters are not allowed as arguments to operator functions. The general form of an operator function is as follows.
public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For overloading the unary operators, there is only one argument and for overloading a binary operator there are two arguments. Remember that at least one of the arguments must be a user-defined type such as class or struct type.
Overloading Unary Operators – the general form of operator function for unary operators is as follows.public static return_type operator op (Type t){// Statements}Where Type must be a class or struct.The return type can be any type except void for unary operators like +,~, ! and dot (.). but the return type must be the type of ‘Type’ for ++and o remember that the true and false operators can be overloaded only as pairs. The compilation error occurs if a class declares one of these operators without declaring the other.
The following program overloads the unary – operator inside the class Complex
// Unary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(\”{0} {1}\”,x,y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
Overloading Binary Operators
An overloaded binary operator must take two arguments, at least one of them must be of the type class or struct, inwhich the operation is defined. But overloaded binary operators can return any value except the type void. The general form of a overloaded binary operator is as follows.
public static return_type operator op (Type1 t1, Type2 t2)
{
//Statements
}
A concrete example is given below
// binary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(\”{0} {1}\”,x,y);
}
public static Complex operator +(Complex c1,Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x+c2.x;
temp.y = c1.y+c2.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}
The binary operators such as = =, ! =, <,>, < =, > = can be overloaded only as pairs. Remember that when a binary arithmetic operator is overloaded, corresponding assignment operators also get overloaded automatically. For example if we overload + operator, it implicitly overloads the + = operator also.
Summary
1.The user defined operator declarations can’t modify the syntax, precedence or associativity of an operator. For example, a + operator is always a binary operator having a predefined precedence and an associativity of left to right.
2.User defined operator implementations are given preference over predefined implementations.
3.Operator overload methods can’t return void.
4.The operator overload methods can be overloaded just like any other methods in C#. The overloaded methods should differ in their type of arguments and/or number of arguments and/or order of arguments.Remember that in this case also the return type is not considered as part of the method signature.
Conclusion
The operator overloading is one of the key concepts of C# and are very interesting aspects of the language. I’ve given you enough information to use operator overloading in your code and shown you some examples.

Monday, May 3, 2010

MANIPULATING STRINGS



Strings
The String  classes provide strings functionality in .NET. 
 Understanding the String Class

The String class implements the functionality of string data type. String class is defined in the System namespace. Here are few important things about the String class before we proceed:
  1. An instance of String is immutable, means once an instance is created, it cannot be modified. There are methods, which returns a new String to return a new sub string from it.
  2. Index of String is zero based. Means the first character of the index is 0th element of the String and last character of the String is total number of elements in the string - 1.
  3. By default a String is an empty string (""). So you don't have to initialize it as you used to do in C++ or other languages. An empty string is greater than the null value.
String class Members

String class provides two properties - Chars and Length. The Chars property returns the character at a specified position in a string and the Length property returns the number of characters in a string.

String class provides two types of methods - static and instance. Static methods can only be used by String class, not by an instance of the String class. The instance methods are used by instances of the String class.
Static Methods of String/string
Compare: Compares the values of two strings.

Concat: Concatenates (joins) two or more strings into one string.

Copy: Creates a new string from an existing string.

Equals :Compares two strings to determine whether they contain the same value. Returns true if the two values are equal; otherwise, returns false.

Join :Concatenates two or more strings. A specified “separator string” is placed between each of the original strings.


Methods and Properties of Each Instance

Clone: Returns a copy of the stored string.

CompareTo: Compares the value of this string with the value of another string. Returns a negative number if this string is less than the compared string, 0 if equal, and a positive number if the value of this string is greater.

CopyTo: Copies a portion of or all of a string to a new string or character array.

EndsWith: Determines whether the end of the value stored in the string is equal to a
string value. If they are equal, true is returned; otherwise, false is returned.
Equals Compares two strings to determine whether they contain the same value.
Returns true if the two values are equal; otherwise, returns false.

IndexOf: Returns the index (location) of the first match for a character or string. Returns
-1 if the value is not found.

Insert :Inserts a value into a string. This is done by returning a new string.

LastIndexOf: Returns the index (location) of the last match for a character or a string.
Returns -1 if the value is not found.

Length: Returns the length of the value stored in the string. The length is equal to the
number of characters contained.

PadLeft: Right-justifies the value of a string and then pads any remaining spaces with a
specified character (or space).

PadRight: Left-justifies the value of a string and then pads any remaining spaces with a
specified character (or space).

Remove: Deletes a specified number of characters from a specified location within a
string.

Split: The opposite of Join. Breaks a string into substrings based on a specified value. The specified value is used as a breaking point.

StartsWith: Determines whether the value stored in a string starts with a specified character
or set of characters. Returns true if there is a match and false if not. If
specified character is null, true is also returned.

Substring: Returns a substring from the original string starting at a specified location. The
number of characters for the substring might also be specified but is not required.

ToCharArray: Copies the characters in the current string value to a char array.

ToLower: Returns a copy of the current value in all lowercase letters.

ToUpper: Returns a copy of the current value in all uppercase characters.

Trim: Removes copies of a specified string from the beginning and end of the current
string.

TrimEnd: Removes copies of a specified string from the end of the current string.

TrimStart: Removes copies of a specified string from the beginning of the current string.

Comparing Strings

The Compare method compares two strings and returns an integer value. The return value of Compare method can be less than zero, greater than zero or equals to zero
 The following code compares two strings and return results on the System console.

// Comparing two strings
//====================================
string str1 = "ppp";
string str2 = "ccc";
int res = String.Compare(str1, str2);
Console.WriteLine("First result:" +res.ToString());
str2 = "ttt"; res = String.Compare(str1, str2);
Console.WriteLine("Second result:" +res.ToString());
str1 = "ttt"; res = String.Compare(str1, str2);
Console.WriteLine("Third result:" +res.ToString));
//====================================

The CompareTo method is an instance method. It compares a value (either a string or on object) with a string instance. Return values of this method are same as the Compare method. The following source code compares two strings.

// CompareTo Method
string str = "kkk";
Console.WriteLine( str.CompareTo(str1) );

Copy and Concatenating Strings

The Concat method adds strings (or objects) and returns a new string. Using Concat method, you can add two strings, two objects and one string and one object or more combinations of these two.

The following source code concatenate two strings.

string str1 = "ppp";
string str2 = "ccc";
string strRes = String.Concat(str1, str2);
Console.WriteLine(strRes);

The following source code concatenates one string and one object.

object obj = (object)12;
strRes = String.Concat(str1, obj);
Console.WriteLine(strRes);

The Copy method copies contents of a string to another. The Copy method takes a string as input and returns another string with the same contents as the input string. For example, the following code copies str1 to strRes.

string str1 = "ppp";
string str2 = "ccc";
string strRes = String.Copy(str1);
Console.WriteLine("Copy result :" + strRes);

The CopyTo method copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. For example, the following example copies contents of str1 to an array of characters. You can also specify the starting character of a string and number of characters you want to copy to the array.

string str1 = "ppp";
char[] chrs = new Char[2];
str1.CopyTo(0, chrs, 0, 2);

The Clone method returns a new copy of a string in form of object. The following code creates a clone of str1.

string str1 = "ppp";
object objClone = str1.Clone();
Console.WriteLine("Clone :"+objClone.ToString());

The Join method is useful when you need to insert a separator (String) between each element of a string array, yielding a single concatenated string. For example, the following sample inserts a comma and space (", ") between each element of an array of strings.

string str1 = "ppp";
string str2 = "ccc";
string str3 = "kkk";
string[] allStr = new String[]{str1, str2, str3};
string strRes = String.Join(", ", allStr);
Console.WriteLine("Join Results: "+ strRes);

Adding, Removing and Replacing Strings

The Insert method inserts a specified string at a specified index position in an instance. For example, the following source code inserts "bbb" after second character in str1 and the result string is "pbbbpp".

string str1 = "ppp";
string strRes = str1.Insert(2, "bbb");
Console.WriteLine(strRes.ToString());

The Remove method deletes a specified number of characters from a specified position in a string. This method returns result as a string. For example, the following code removes three characters from index 3.

string s = "123abc000";
Console.WriteLine(s.Remove(3, 3));

The Replace method replaces all occurrences of a specified character in a string. For example, the following source code replaces all p character instances of str1 with character l and returns string "lll".

string str1 = "ppp";
string repStr = str1.Replace('p', 'l');
Console.WriteLine("Replaced string:"+ repStr.ToString() );

The Split method separates strings by a specified set of characters and places these strings into an array of strings. For example, the following source code splits strArray based on ',' and stores all separated strings in an array.

string str1 = "ppp";
string str2 = "ccc";
string str3 = "kkk";
string strAll3 = str1 + ", " +str2+", "+str3 ;
string[] strArray = strAll3.Split(',');
foreach (string itm in strArray)
{
Console.WriteLine(itm.ToString() );
}

Uppercase and Lowercase
The ToUpper and ToLower methods convert a string in uppercase and lowercase respectively. These methods are easy to use. The following code shows how to use ToUppler and ToLower methods.

string aStr = "adgas";
string bStr = "ABNMDWER";
string strRes = aStr.ToUpper();
Console.WriteLine("Uppercase:"+ strRes.ToString());
strRes = bStr.ToLower();
Console.WriteLine("Lowercase:"+ strRes.ToString());
Formatting Strings

You can use the Format method to create formatted strings and concatenate multiple strings representing multiple objects. The Format method automatically converts any passed object into a string.

For example, the following code uses integer, floating number and string values and format them into a string using the Format method.

Listing 1: Using Format method to format a string

int val = 7;
string name = "Mr. John";
float num = 45.06f;
string str = String.Format ("Days Left : {0}. Current DataTime: {1:u}. \n String: {2}, Float: {3}" , val, DateTime.Now, name, num);
Console.WriteLine(str);
Trimming and Removing Characters from Strings

The String class provides Trim, TrimStart and TrimEnd methods to trim strings. The Trim method removes white spaces from the beginning and end of a string. The TrimEnd method removes characters specified in an array of characters from the end of a string and TrimStart method removes characters specified in an array of characters from the beginning of a string.

You can also use the Remove method to remove characters from a string. The Listing 2 code shows how to use these methods.
String str = " C# ";
Console.WriteLine("Hello{0}World!", str);
string trStr = str.Trim();
Console.WriteLine("Hello{0}World!", trStr );
str = "Hello World!";
char[] chArr = {'e', 'H','l','o',' ' };
trStr = str.TrimStart(chArr);
Console.WriteLine(trStr);
str = "Hello World!";
char[] chArr1 = {'e', 'H','l','o',' ' };
trStr = str.TrimEnd(chArr1);
Console.WriteLine(trStr);
string MyString = "Hello Delta World!";
Console.WriteLine(MyString.Remove(5,10));

Padding Strings

The PadLeft and PadRight methods can be used to pad strings. The PadLeft method right-aligns and pads a string so that its rightmost character is the specified distance from the beginning of the string. The PadRight method left-aligns and pads a string so that its rightmost character is a specified distance from the end of the string. These methods return new String objects that can either be padded with empty spaces or with custom characters. Listign 3 shows how to use these methods.

Listing 3: Using padding methods
string str1 = "My String";
Console.WriteLine(str1.PadLeft(20, '-'));
string str2 = "My String";
Console.WriteLine(str2.PadRight(20, '-'));