Updated: Jan 18
When writing our code, we can use the variable of 'char' to add a single character. However, what can we do when adding a collection of characters? To support this option, we can 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 has its properties and methods that we can use to work and manipulate strings. I will review some of the main properties/methods worth learning in the paragraph below.
Below, a list of the most important special characters you will need to know when working with strings.
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:
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:
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 a 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).
This method combines multiple strings into a single one (supported in an array and generic list as well).
Removing chars from a string
The string 'Remove' method removes 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 two 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 search to identify a specific word or a sentence in our string. To do it, we can use the 'Contains' method.