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

  1. //Ways of creating string;  
  2. string name = "Abhishek"//With help of Literals  
  3. string surname = "Yadav";  
  4. string fullName = name + surname; //Concatenating 2 strings   
  5. Console.WriteLine("Full Name: {0}", fullName);  
  6. Console.WriteLine("Enter your String:"); //Taking input from Keyboard;  
  7. string text = Console.ReadLine();  
  8. int marks = 65;  
  9. 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 

  1. //Static Methods:  
  2. Console.WriteLine("================= Static Methods ================\n");  
  3. Console.WriteLine("Comparing \"abhishek\" and \"Sunny\" {0}",string.Compare("abhishek","Sunny"));  
  4. Console.WriteLine("Copying text value in new string: {0}",string.Copy(text));  
  5. Console.WriteLine("Is \"Apple\" and \"apple\" are equal ??: {0}",string.Equals("Apple","apple"));  
  6. Console.WriteLine("Is text is NULL ? : {0}",string.IsNullOrEmpty(text));  
  7. //All Instance Methods:  
  8. Console.WriteLine("\n================= Static Methods ================\n");  
  9. string cloneText = (string)text.Clone();  
  10. Console.WriteLine("Clone Text: {0}",cloneText);  
  11.   
  12. bool containText = text.Contains("e");  
  13. Console.WriteLine("Is text contains given value?: {0}",containText);  
  14.   
  15. string removedText = text.Remove(2);  
  16. Console.WriteLine("New string after Removing: {0}",removedText);  
  17.   
  18. if (text.Contains("e"))  
  19. {  
  20.     string replacedText = text.Replace("e","E");  
  21.     Console.WriteLine("New String after Replacing character: {0}", replacedText);  
  22. }  
  23.   
  24. string insertedText = text.Insert(3, " Added String ");  
  25. Console.WriteLine("Inserted Text: {0}",insertedText);  
  26. string subString = text.Substring(3, 8);  
  27. 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.

StringBuilder

Syntax for creating a new string with the StringBuilder class:

  1. StringBuilder str1 = new StringBuilder();
  2. 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

  1. StringBuilder str1 = new StringBuilder("Welcome");  
  2. str1.Append(" to");  
  3. str1.Append(" C-Sharp");  
  4. str1.Append("Corner");  
  5. 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.

  1. string normalStr = String.Empty;  
  2. StringBuilder dynamicString = new StringBuilder();  
  3.   
  4. for (int i = 0; i < 20000; i++)  
  5. {  
  6.     normalStr = normalStr + "Abhishek" + i.ToString();  
  7. }  
  8.   
  9. for (int i = 0; i < 20000; i++)  
  10. {  
  11.     dynamicString.Append("Abhishek" + i.ToString());  
  12. }  
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.