In this lesson, you learn some interesting properties of strings, as well as several helper methods available via the string class that will allow you to perform a variety of useful processes on strings.

Step 1: Create a New Project

Begin this lesson by creating a new ASP.NET project called “CS-ASP_035” with the following programmatic IDs and Server Controls:

  1. valueTextBox

  2. okButton

  3. resultLabel


In okButton_Click() let’s first output a simple message within HTML:


You will see that there is a conflict between the double-quotes used for the HTML and the double-quotes used for the entire string. It’s easy to see why this is a problem: the compiler thinks that the string is ending with a second double-quote when the first double-quote is referenced in the HTML tag:

<p style=”color:#ee3b32;”>

Step 2: Make a Character Literal with Backslash

This is fixed by having the compiler read the HTML quotes as literal quotes, and is achieved by using escape characters. In this case, by placing a backslash before them, thereby “escaping” the string sequence. You can use the backslash in such a way to turn any character in a string into a literal character:


Another common solution to this problem is to use double-quotes for strings and single-quotes for HTML:



Step 3: Handling a String as an Array of Char

It’s common when parsing through a string to want to isolate a single character. You can do this quite easily because a string is actually made up of an array of characters of type char. Here, we’re going to output the third character in the string by accessing its index, and using the ToString() method:



Step 4: StartsWith(), EndsWith() and Contains() String Helper Methods

Another common need is to parse through a string to find out some particular nformation that it contains. Here are a few useful helper methods to this end:


Step 5: Using IndexOf() for Finding Position of a String Sequence

You can also find the indexed position of a particular string sequence within an entire string:



Step 6: Using Insert() to Insert a New Substring

And then you can use that index information to insert a new string at that position:



Step 7: Using Remove() to Remove a Substring

You can also (1) remove a number of characters beginning at a particular (2) index position in the string. In this example, we’re removing the remaining characters in the string by calculating the
string length, minus the starting position index:


Step 8: Using Substring() to Return a Substring Sequence

And here we use the Substring() method to return the string sequence we are looking for, along with the rest of the string that comes after it, minus the last character:



Step 9: Using Trim()Remove Whitespace

It’s common to want to isolate a string and then trim any whitespace or empty characters. The easiest way to do this is with the Trim() method:



Here we trimmed off two empty spaces from both the beginning and the end of the string. You could also just trim these two opposite sides individually with the TrimStart() and TrimEnd() methods, respectively.

Step 10: Using PadLeft() and PadRight() to Add Whitespace

You can also do the opposite of trimming by adding padding to the string sequence with the PadLeft() and PadRight() methods. The PadLeft() method adds (1) the number of spaces in which characters are added to the left of the string sequence and (2) the character placed in that padded space (note that this value is of type char, so it has to be enclosed in single-quotes):



Note: The integer totalWidth input parameter for PadLeft() and PadRight() evaluates the width of the entire string. In this case, if we typed in ‘Bob’ for the TextBox and pressed OK, we would have 7 ‘*’ characters preceding it, because totalWidth is equal to 10, and ‘Bob’ has a length of 3.

Suppose that you want to check if one string is equivalent to another string but you want to ignore case sensitivity. Strings are normally case sensitive, so something like this will evaluate as false:


Step 11: Using ToUpper() to Bypass Case Sensitivity

A common solution to this is to set all characters in the string to upper-case, or lower-case (here we’re also trimming the string for good measure):



If we type in "bob" to the TextBox, even though the input is not equivalent to the literal string, when the conversion is completed, they will be equal.

Step 12: Using Replace() To Apply Templated String Formatting

It’s very common to have to replace characters within a string that doesn’t match the formatting requirements of your application. Here, we’re using the Replace() method to modify an existing string:



Step 13: Using Split() to Split a String into String[] Array

Another useful task is splitting up a string into an array of smaller strings based on some form of de-limiter (such as a comma, dash, and so on). The code below is (1) splitting the values entered by the user wherever there is a comma and (2) iterating through the array items adding each to string result along with (3) the length of the current string:





All of these string manipulation methods work based on the same principles that we saw in the previous lessons on arrays. Because a string is an array of characters, it is subject to the same constraints of immutability that other arrays face (arrays can’t inherently resize, remove, elements, etc). So whenever you want to change an aspect of a string, it has to go through the process arrays go through of copying values from one array to another but with x number of elements more/less, etc. Be aware that as you manipulate strings over and over again you are adding more and more processing, and memory, load.

Step 14: Using the StringBuilder Class

There is a built-in class within the .NET Framework – called StringBuilder – that makes certain processes on strings more efficient.
Here is how you create a StringBuilder object/variable:

StringBuilder sb = new StringBuilder();

However, Intellisense will show that it doesn’t have access to the StringBuilder class (there will be red squiggly underlines). You will have to add a reference to point to that information and the easiest way to do this is to click on the underline and enter the following keys to get a references menu to pop-up:



Step 15: Add the Using Declaration to Access StringBuilder Class

Add the “using System.Text;” reference to your project by clicking on it and it will be added to the top of the Default.aspx.cs file (more on using declarations and namespaces in later lessons):


Now that we can reference the StringBuilder class, let’s re-create the previous process but with the more efficient StringBuilder Append() method:



It’s worth noting that the StringBuilder optimization is best used when there is an intensive process involved. If you are manipulating a few strings over a short duration of time, then you can use the ordinary string methods without seeing any significant reduction in performance. There are specific tools you can use to measure the performance of your code and respond with optimizations to remove bottlenecks. However, that is best left for when you know how to use the tools and spot low-performant code.

Lessons in this Course