Understanding C# Strings: A Comprehensive Guide
Summary of C# Strings
Introduction to Strings
- Definition: Strings are sequences of characters used to represent text in C#.
- Data Type: In C#, a string is an object of the
System.String
class.
Creating Strings
- Strings can be created using:
- Double quotes:
string greeting = "Hello, World!";
- String interpolation:
string name = "Alice"; string message = $"Hello, {name}!";
- Double quotes:
Key Concepts
- Immutable: Strings in C# are immutable, meaning once created, their value cannot be changed.
- Concatenation: You can combine strings using the
+
operator orString.Concat
method.- Example:
string fullName = firstName + " " + lastName;
- Example:
String Methods
- C# provides various built-in methods for string manipulation:
- Length:
int length = myString.Length;
- Substring: Extracts a part of the string. Example:
string sub = myString.Substring(0, 5);
- ToUpper() / ToLower(): Converts the string to upper or lower case.
- Example:
string upper = myString.ToUpper();
- Example:
- IndexOf(): Finds the position of a character or substring.
- Example:
int index = myString.IndexOf("World");
- Example:
- Replace(): Replaces occurrences of a specified string.
- Example:
string newStr = myString.Replace("World", "C#");
- Example:
- Length:
String Formatting
- Strings can be formatted using:
- String Format:
string formatted = String.Format("Hello, {0} !", name);
- Interpolation: As shown in the creation example above.
- String Format:
Escape Sequences
- Special characters in strings can be represented using escape sequences, such as:
\n
for new line\t
for tab\\
for backslash
Conclusion
- Strings are a fundamental part of C# programming, and understanding how to manipulate them is crucial for effective coding.
Example Code
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
This summary provides a fundamental overview of strings in C#, designed for beginners to grasp the essential concepts and usage.