C# - Strings
In C#, strings are sequences of characters used to represent text. They are a fundamental part of programming and come with a variety of methods and properties for manipulating and analyzing text. Here’s a detailed guide on working with strings in C#:
1. Declaring and Initializing Strings
You can declare and initialize strings using double quotes.
Syntax:
csharpstring str = "Hello, World!";
2. String Operations
Concatenation
You can concatenate strings using the + operator or the String.Concat method.
csharpstring firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
Interpolation
String interpolation provides a way to embed expressions within string literals, using curly braces {}.
csharpstring name = "Alice";
int age = 30;
string message = $"Name: {name}, Age: {age}"; // "Name: Alice, Age: 30"
Formatting
You can use String.Format to create formatted strings.
csharpstring formatString = "Name: {0}, Age: {1}";
string formattedMessage = String.Format(formatString, name, age); // "Name: Alice, Age: 30"
3. Common String Methods
Length
Gets the number of characters in the string.
csharpint length = str.Length; // Length of the string
Substring
Extracts a substring from the string.
csharpstring sub = str.Substring(7, 5); // "World"
IndexOf
Finds the index of the first occurrence of a specified substring.
csharpint index = str.IndexOf("World"); // 7
Replace
Replaces all occurrences of a specified substring with another substring.
csharpstring replaced = str.Replace("World", "C#"); // "Hello, C#!"
ToUpper and ToLower
Converts the string to uppercase or lowercase.
csharpstring upper = str.ToUpper(); // "HELLO, WORLD!"
string lower = str.ToLower(); // "hello, world!"
Trim
Removes leading and trailing whitespace from the string.
csharpstring trimmed = " Hello ".Trim(); // "Hello"
Split
Splits the string into an array of substrings based on a delimiter.
csharpstring[] words = str.Split(' '); // ["Hello,", "World!"]
Join
Concatenates elements of an array into a single string with a specified delimiter.
csharpstring[] names = { "John", "Jane", "Doe" };
string joined = String.Join(", ", names); // "John, Jane, Doe"
Contains
Checks if a specified substring is present in the string.
csharpbool contains = str.Contains("World"); // true
4. String Comparison
Strings can be compared using various methods, such as Equals, Compare, and CompareOrdinal.
Equals
Compares the string with another string for equality.
csharpbool isEqual = str.Equals("Hello, World!"); // true
Compare
Compares two strings and returns an integer indicating their relative order.
csharpint comparison = String.Compare("apple", "banana"); // < 0
CompareOrdinal
Compares two strings using ordinal (culture-insensitive) comparison.
csharpint ordinalComparison = String.CompareOrdinal("apple", "banana"); // < 0
5. String Builder
For scenarios where you need to perform many modifications to a string, consider using StringBuilder. It is more efficient than using string concatenation in a loop.
csharpusing System.Text;
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string result = sb.ToString(); // "Hello World"
6. Escape Sequences
Use escape sequences to represent special characters within strings.
\": Represents a double quote.\\: Represents a backslash.\n: Represents a newline.\t: Represents a tab.
csharpstring text = "He said, \"Hello, World!\"\nThis is a new line.";
7. Verbatim Strings
Verbatim strings, defined with @, ignore escape sequences and allow multi-line strings.
csharpstring path = @"C:\Users\Name\Documents";
string multiLine = @"Line 1
Line 2
Line 3";
8. String Interpolation (Advanced)
String interpolation supports more advanced formatting options.
csharpdecimal price = 123.4567m;
string formattedPrice = $"Price: {price:C2}"; // "Price: $123.46"
Summary
In C#, strings are powerful and versatile for handling text. You can perform a wide range of operations, from basic concatenation and formatting to advanced manipulations using methods like Substring, Replace, and Split. For efficient string modifications, use StringBuilder. Understanding and using these string operations effectively will enhance your ability to work with text in C# applications.