Strings in C# .NET

Introduction

This article explains what strings are, including the types of strings, how to create strings, the String and StringBuilder classes themselves and will compare the performance of both of the classes.

As we all know, String Manipulation is the most common part of C# Programs. Strings represent a sequence of characters. C# supports the following 2 types of strings:

  1. Immutable Strings
    Immutable Strings are the strings whose content cannot be modified after the string has been created. And when we modify a string using string methods like Replace(), ToUpper(), ToLower() it seems that the string value has been changed, but actually it returns a new String object that contains the modified string value.
     
  2. Mutable Strings
    The content of Mutable Strings can be modified.

C# defines a predefined reference type known as string that is an alias of the System.String class in the Common Language Runtime (CLR).

The CLR maintains a table called “Intern Pool” that holds a single reference to each text value used by the program. A String variable that refers to a specific piece of text is actually a reference to the intern pool.

I'll talk more about the “Intern pool” and “String Pooling in C#” in my next article.

Using a string alias, we can create or declare string type objects. When we declare a string using the string type, we are actually declaring the object of type System.String class.

How to Create C# Strings

We can create immutable strings in many ways, as shown in the following table:

Ways of creating string Example
using Literals string str1; str1 = “Abhishek”
Concatenating 2 strings string s1 = “Abhishek”; string s2 = “Yadav”; string s3 = s1+s2;
Reading inputs from Keyboard string name = Console.ReadLine();
using ToString() method int marks = 85; string sMarks = marks.ToString();

Examples

//Ways of creating string;  
string name = "Abhishek"; //With help of Literals  
string surname = "Yadav";  
string fullName = name + surname; //Concatenating 2 strings   
Console.WriteLine("Full Name: {0}", fullName);  
Console.WriteLine("Enter your String:"); //Taking input from Keyboard;  
string text = Console.ReadLine();  
int marks = 65;  
string myMarks = marks.ToString(); // String created with ToString() method.

There're other ways also, I mean using string functions also we can create new strings.

String Methods

The String class provides various methods to play with your string. The following table will show some of the static as well as non-static methods provided by the String Class.

Static String Methods
Method Description
Compare(string string1m string string2) This method returns an int value, if string1 is smaller than string2 then it returns -1, if string1 is larger than string2 then it returns 1, if both strings are equal then it returns 0
Copy(string str1) Create a new string same as string1.
Equals(string str1, string str2) Returns true if both strings are equal.
IsNullOrEmpty(string str1) Returns true if string contains blank or null value.
IsNullOrWhiteSpace(string str1) Returns true if string contains blank, null or any whitespace characters.

The String class also provides some instance methods, please find the following table for that.

Instance String Methods
Method Description
Clone() Creates a new string. Same as Copy()
Contains(string value) Returns true if string contains specified value.
Remove(int startIndex) Removes the character from startIndex.
ToCharArray() Returns an array of char of given string.
Replace(char old, char new) Replace old letter/string with new specified one.
Insert(int startIndex, string newString) Insert new string at given index.
SubString(int startIndex, int length) Returns a new string from startIndex to given length.

Examples 

//Static Methods:  
Console.WriteLine("================= Static Methods ================\n");  
Console.WriteLine("Comparing \"abhishek\" and \"Sunny\" {0}",string.Compare("abhishek","Sunny"));  
Console.WriteLine("Copying text value in new string: {0}",string.Copy(text));  
Console.WriteLine("Is \"Apple\" and \"apple\" are equal ??: {0}",string.Equals("Apple","apple"));  
Console.WriteLine("Is text is NULL ? : {0}",string.IsNullOrEmpty(text));  
//All Instance Methods:  
Console.WriteLine("\n================= Static Methods ================\n");  
string cloneText = (string)text.Clone();  
Console.WriteLine("Clone Text: {0}",cloneText);  
  
bool containText = text.Contains("e");  
Console.WriteLine("Is text contains given value?: {0}",containText);  
  
string removedText = text.Remove(2);  
Console.WriteLine("New string after Removing: {0}",removedText);  
  
if (text.Contains("e"))  
{  
    string replacedText = text.Replace("e","E");  
    Console.WriteLine("New String after Replacing character: {0}", replacedText);  
}  
  
string insertedText = text.Insert(3, " Added String ");  
Console.WriteLine("Inserted Text: {0}",insertedText);  
string subString = text.Substring(3, 8);  
Console.WriteLine("New string after SubString(): {0}",subString);

After running the code above you'll get the following output: 

String Methods in C#

Until now, we saw Immutable Strings that are created by the System.String class.

Now, we'll see how to deal with Mutable Strings.

As we know, mutable strings are those strings whose content can be changed or modified in place; this can be done using the StringBuilder class.

C# StringBuilder

Syntax for creating a new string with the StringBuilder class:

StringBuilder str1 = new StringBuilder();
StringBuilder str2 = new StringBuilder(“Abhishek”);

Here, we've created 2 objects of StringBuilder. The first object, in other words str1, is created with an Empty string and the str2 object is created with an initial size of 8 characters.

Mutable Strings are also known as a “Dynamic String”. It stores character data in an array and can add, remove, replace and append characters without creating a new string object.

The StringBuilder class also provides some methods. Some of the methods are shown in the following table.

Method Description
Append Appends a string to the end of the StringBuilder's text.
Remove Removes a range of character from StringBuilder's text.
Replace Replace old letter/string with new specified one.
Clear Removes all the character from the current StringBuilder instance.

Example

StringBuilder str1 = new StringBuilder("Welcome");  
str1.Append(" to");  
str1.Append(" C-Sharp");  
str1.Append("Corner");  
Console.WriteLine(str1);  

Output 

String Builder in CSharp

In the above program, a StringBuilder object is created with initial size of 7 characters, using the Append() method, a string is appended to the str1 object. So, it's not creating a new string; instead, it modifies the string.

Performance

Performance wise the StringBuilder class is slightly faster than the String class. To check the performance in both of the ways (in other words System.String and StringBuilder), I tried to concatenate 20000 strings with the StringBuilder object and System.String using a for loop.

string normalStr = String.Empty;  
StringBuilder dynamicString = new StringBuilder();  
  
for (int i = 0; i < 20000; i++)  
{  
    normalStr = normalStr + "Abhishek" + i.ToString();  
}  
  
for (int i = 0; i < 20000; i++)  
{  
    dynamicString.Append("Abhishek" + i.ToString());  
}

In the code above, we've created a string literal and a StringBuilder object. In the first for loop, we are trying to concatenate a string 20000 times with a string literal and the same thing with a StringBuilder object as well in the second for loop.

After diagnosing both (using System.Diagnostics), we found the following output with a big difference the methods. 

Perfomanence in CSharp

System.String took 4.4576779 seconds to concatenate 20000 strings
StringBuilder took only 0.0048251 seconds to concatenate 20000 strings.

Conclusion

You can create mutable and immutable strings in .NET using String and StringBuilder classes as per your requirements. Various methods are available to manipulate these strings. We learned how to create strings and how to manipulate those strings (mutable and immutable strings). We also checked the performance of the String class and the StringBuilder class.

I hope this article helps you to understand the concept of strings.

If there's any mistake in this article then please let me know. Please provide your valuable feedback and comments, that enable me to provide a better article the next time.


Recommended Free Ebook
Similar Articles