In this lesson, you will learn about Strings in C#, string operations, and examples to better understand the topic.
A string variable is a collection of characters inside a double quote. For example:
string name = "John";
Strings are used to store Alphanumeric values. They are immutable, which means they cannot be changed once created. Instead, a new string object is created in the memory to store the new value.
Manipulating a string too many times may result in a performance issue. For this purpose, we can use the String Builder Class, which we discuss later in this course.
The string type contains useful built-in functions. Below are some of the string functions that most developers should be aware of:
To return the length of a string, you can simply use the
Length method as shown in the example below:
Another useful method in the string type is the
ToUpper() method, which transforms the string characters into uppercase letters. Example:
ToLower() method is the opposite of the ToUpper(); it transforms all the characters in a string into Lowercase letters. Example:
The Concat method Concat two strings or more into one string. Example:
Another way to contact string in C# is to use the + Operator. For Example:
This method returns an integer value of the index position of a given character in a string. For Example:
Substring method extracts characters from a string, starting from the index, and returns the result in a new string object. For Example:
Since a string variable is a collection of characters, you can access a specific character by referring to its index, starting from position 0. For example
You can access the characters in a string by referring to its index number inside square brackets
As we already know, strings are surrounded by two double Quote “”. But what if the string itself contains double quotes? Example:
string myString = "I am studying "C#" using a great course!";
The string “C#” will confuse the compiler and generate an error. In this case, we add the backslash
\ to escape the special character right before each double-quote. Example:
The escaping character is useful for strings containing double quotes “, single quotes, and backslashes. For Example:
Also, the C# programming language offers more escaping characters, as shown in the example below:
This concludes the C# Strings lesson. In the next lesson, you will learn about the StringBuilder Class in C#.