Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Strings in C#

What is a String?

In C#, a string is a sequence of characters. It is used to represent text. Strings in C# are objects of the System.String class. Strings are immutable, which means once they are created, their value cannot be changed.

Creating Strings

Strings can be created in several ways in C#. The simplest way is to declare a string variable and assign it a string literal.

Example:

string greeting = "Hello, World!";

String Concatenation

Concatenation is the process of joining two or more strings together. In C#, you can use the + operator to concatenate strings.

Example:

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
Output: John Doe

String Interpolation

String interpolation is a method of concatenating strings using placeholders. It is more readable and convenient than using the + operator. In C#, you use the $ symbol before the string and place expressions inside curly braces {}.

Example:

string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
Console.WriteLine(fullName);
Output: John Doe

String Methods

The System.String class provides many methods for working with strings, such as Length, ToUpper, ToLower, Substring, and Replace.

Example:

string phrase = "Hello, World!";
int length = phrase.Length;
string upperPhrase = phrase.ToUpper();
string lowerPhrase = phrase.ToLower();
string subPhrase = phrase.Substring(7, 5);
string replacedPhrase = phrase.Replace("World", "C#");
Console.WriteLine($"Length: {length}");
Console.WriteLine($"Upper: {upperPhrase}");
Console.WriteLine($"Lower: {lowerPhrase}");
Console.WriteLine($"Substring: {subPhrase}");
Console.WriteLine($"Replaced: {replacedPhrase}");
Output:
Length: 13
Upper: HELLO, WORLD!
Lower: hello, world!
Substring: World
Replaced: Hello, C#!

Escape Sequences

Escape sequences are special characters used in strings to represent certain whitespace characters, such as a newline \n, a tab \t, or a backslash \\.

Example:

string text = "First Line\nSecond Line\tTabbed Text\\Backslash";
Console.WriteLine(text);
Output:
First Line
Second Line Tabbed Text\Backslash

Verbatim Strings

Verbatim strings in C# are prefixed with the @ symbol, which allows you to include newline characters and escape sequences within the string without needing to use escape characters.

Example:

string path = @"C:\Users\JohnDoe\Documents";
string multiLineText = @"First Line
Second Line
Third Line";
Console.WriteLine(path);
Console.WriteLine(multiLineText);
Output:
C:\Users\JohnDoe\Documents
First Line
Second Line
Third Line