Lesson 35 - Manipulating Strings

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

Get GitHub Code

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.

Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment