Working with Strings
Introduction
In C#, a string is a sequence of characters. Strings are used for storing text and are an important part of most programming tasks, making them essential for any beginner to understand and master. In this tutorial, we will go through the basics of working with strings in C#.
Creation of Strings
To define a string in C#, you can use the following syntax:
string myString = "Hello World!";
In this case, myString
is a variable that holds a string value - "Hello World!".
String Concatenation
Concatenation means joining two or more strings together. In C#, you can use the +
operator to concatenate strings:
string string1 = "Hello, ";
string string2 = "World!";
string greeting = string1 + string2; // "Hello, World!"
String Length
To get the length of a string (the number of characters), use the Length
property:
string myString = "Hello World!";
int length = myString.Length; // 12
String Methods
C# provides a variety of string methods that you can use to manipulate and work with strings. Here are a few examples:
ToUpper()
and ToLower()
These methods convert a string to uppercase and lowercase, respectively:
string myString = "Hello World!";
string upper = myString.ToUpper(); // "HELLO WORLD!"
string lower = myString.ToLower(); // "hello world!"
Trim()
This method removes whitespace from the beginning and end of a string:
string myString = " Hello World! ";
string trimmed = myString.Trim(); // "Hello World!"
Substring()
This method extracts a part of a string. It takes two parameters: the start index and the length of the substring:
string myString = "Hello World!";
string substring = myString.Substring(0, 5); // "Hello"
String Interpolation
Interpolation is a convenient way to embed variables directly into strings. You can use the $
symbol before a string to interpolate variables:
string name = "John";
string greeting = $"Hello, {name}!"; // "Hello, John!"
String Equality
To check if two strings are equal, you can use the ==
operator. This compares the strings character by character:
string string1 = "Hello";
string string2 = "Hello";
bool areEqual = string1 == string2; // true
Remember that string comparison in C# is case-sensitive.
Conclusion
Working with strings is fundamental in C# programming. This tutorial introduced you to the basics of creating, concatenating, and manipulating strings. We also covered important string methods and features such as string interpolation and equality. With consistent practice, you'll soon become proficient in working with strings in C#.