Lesson #2 - C# String with Examples

Updated: Dec 13, 2020

When writing our code we can use the variable of ‘char’ to add a single character. However, what can we do when there is a need to add a collection of characters? To support this option we can simply use the ‘string’ variable which represents an array of characters that can be used to build a single word OR a complete sentence.


A sting in c# is an ‘Object’ inherited from the “System.string” class which means that it has its properties and methods that we can use to work and manipulate strings. In the paragraph below, I will review some of the main properties/methods that worth learning.

Special characters

Below, a list of the most important special characters you will need to know when working with strings.

String Length

To discover what is the length of a given string, we can use the ‘Length’ property:

String conversion (uppercase or lowercase)

we can use the “ToUpper” and “ToLower” methods which returns a copy of the string converted to uppercase or lowercase:

String compare

In some cases, we will need to compare two strings as part of the app's regular flow. This can be done in a few ways:

String as Array

A string is an array of chars, therefore we can use different methods and properties related to arrays. let's see some examples:

String Copy

When assigning a string to a string (string A = String B) string A will now get the reference to the value of sting B in the heap, which means that we don’t create a new string in this case. To overcome this issue, we can use the ‘copy’ method which is used to create a replica of the original string (and not just a reference).

String Join

This method is used to combine multiple strings into a single one (supported in an array and generic list as well).

Removing chars from a string

The string ‘Remove’ method is used to remove a specific char from a string.

Replacing values in a string

The replace method is used to replace the inner values of a string.

Strings and Whitespaces

Sometimes we will need to remove unwanted spaces in a given string. To do it, we will use the ‘Trim’ methods:

TrimStart – Delete all spaces at the Start of the word.

TrimEnd - Delete all spaces at the End of the word.

Trim – a combination of the first 2 methods.

Validating string with Start/End word

In some scenarios, we will need to check if there is a specific syntax at the start/end of the string. To do it, we can use the StartsWith and EndsWith methods (method returns a Boolean value (True OR False).

Searching for a specific string

In some scenarios, we will need to run a search to identify a specific word or a sentence in our string. To do it, we can use the ‘Contains’ method.

2 views0 comments