Strings in C# Part 2


In Part 1 of this series, C# Strings, I discussed basics of strings and some string operations such as adding, removing, inserting, comparing, cloning, and replacing strings. In this part, I will discuss some remaining methods of the String class and how to use them. Some of these methods are Format, Trim, TrimEnd, PadLeft, and PadRight.

After discussing these methods, I will discuss the StringBuilder class.

Initializing a String

Before I discuss remaining (left from Part 1) methods of String class, let's see different ways to construct a string.

Actually String class provides eight-overloaded form of constructor methods. These constructors are described in Table 1.
 

Constructor Description
unsafe public String(char*); Creates a new instance from a specified pointer to an array of Unicode characters.
public String(char[]); Creates a new instance from an array of Unicode characters.
unsafe public String(sbyte*); Creates a new instance from a pointer to an array of 8-bit signed integers.
public String(char, int); Creates a new instance from a Unicode character repeated a specified number of times.
unsafe public String(char*, int, int); Creates a new instance from an array of Unicode character, a starting character position within that array and a length.
public String(char[], int, int); Create a new instance from an array of Unicode characters, a starting character position within the array and a length.
unsafe public String(sbyte*, int, int); Create a new instance from an array of 8-bit signed integer, a starting character position within the array and a length.
unsafe public String(sbyte*, int, int, Encoding); Create a new instance from a pointer of array of 8-bit signed integer, a starting character position within the array and a length and an Encoding Object.

Table 1: The String class constructors

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);


The output of Listing 1 is shown Figure 1.



Figure 1.

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, '-'));

The output of Listing 3 is shown in Figure 2.



Figure 2.

The StringBuilder Class

The StringBuilder class represents a mutable string of characters. It's called mutable because it can be modified once it has been created by using Append, Insert, Remove, and Replace methods.

The StringBuilder class is defined in the System.Text namespace. Before you use the StringBuilder class make sure you add the following line in your application:

using System.Text;

Table 2 describes the StringBuilder class properties

Property Description
Capacity Represents the maximum number of characters that can be contained in the memory allocated by the current instance.
Chars Represents the character at the specified position.
Length Represents the number of characters.
MaxCapacity Returns the maximum capacity.

Table 2: The StringBuilder class properties

Table 3 describes the StringBuilder class methods

Method Description
Append Appends a string at the end of this string.
AppendFormat Appends a formatted string.
EnsureCapaciry Ensures that the capacity of string is as specified value.
Inserts Inserts string at the specified position.
Remove Removes a range of characters from the string.
Replace Replaces all occurrences of a character from the string.

Table 3. The StringBuilder class methods.

Using StringBuilder properties and methods is pretty simple. Listing 4 uses StringBuilder class to append, insert, remove and replace characters of a string.

Listing 4. Using StringBuilder class to append, add, replace and remove characters

StringBuilder builder = new StringBuilder("Hello C# World!", 20);
StringBuilder builder = new
StringBuilder("Hello C# World!", 20);
int
cap = builder.EnsureCapacity(55);
builder.Append(". This is a class test.");
Console.WriteLine(builder);
builder.Insert(26," String Builder");
Console.WriteLine(builder);
builder.Remove(5, 9);
Console.WriteLine(builder);
builder.Replace('!', '?');
Console.WriteLine(builder);
Console.WriteLine("Length of string is:" + builder.Length.ToString() );
Console.WriteLine("Capacity of string is:" + builder.Capacity.ToString() );

The output of Listing 4 is shown in Figure 3.



Figure 3.

Performance Note: Whenever you need to do multiple (say more than 5) string operations such as concatenating or adding strings five times to build a large string, it is recommended to use the StringBuilder class and its methods.

About Source Code

Downlaod and unzip the attached cs files. Create a Windows console application using VS.NET and type the code. If you're compiling code from command line, compile cs files with no changes. Make sure you add reference to the System.Text references when compiling StringBuilder sample.

Summary

In this article, I discussed some methods of String, basics of StringBuilder class and how to use StringBuilder class to add, insert, append and remove items from strings. In part 3 of this series, I convert part 1 and part 2 articles to VB.NET.
 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.