C# Strings
Introduction to Strings
In C#, a string is a sequence of characters. Strings are used to store text such as words, sentences, or any other character data. C# strings are objects of type System.String, which provides many methods for safely creating, manipulating, and comparing strings.
Important String Characteristics:
- Strings are reference types, but are immutable (cannot be changed after creation)
- String literals are enclosed in double quotes
"example" - C# provides extensive built-in functionality for string manipulation
- String operations are optimized through string interning and the StringBuilder class
Creating Strings
There are multiple ways to create strings in C#:
String Declaration and Initialization:
// Using string literals
string firstName = "John";
string lastName = "Doe";
// Using the String constructor
string greeting = new string('*', 10); // Creates "**********"
// Empty and null strings
string empty = ""; // Empty string (length = 0)
string empty2 = String.Empty; // Also an empty string
string nullString = null; // Null string (no object reference)
It's generally more efficient to use string literals rather than the String constructor. The string keyword is an alias for the System.String class.
String Concatenation
Joining strings together is called concatenation. C# provides several ways to concatenate strings:
Concatenation Methods:
// Using the + operator
string fullName = firstName + " " + lastName; // "John Doe"
// Using string.Concat method
string fullNameConcat = string.Concat(firstName, " ", lastName); // "John Doe"
// Using StringBuilder for efficient multiple concatenations
using System.Text;
StringBuilder sb = new StringBuilder();
sb.Append(firstName);
sb.Append(" ");
sb.Append(lastName);
string fullNameBuilder = sb.ToString(); // "John Doe"
When concatenating many strings in a loop, the StringBuilder class is more efficient because it avoids creating multiple intermediate string objects.
String Interpolation
String interpolation provides a more readable and convenient syntax to create formatted strings. It's available in C# 6.0 and later.
Using String Interpolation:
string firstName = "John";
string lastName = "Doe";
int age = 30;
// String interpolation with $
string message = $"Name: {firstName} {lastName}, Age: {age}";
// "Name: John Doe, Age: 30"
// With expressions
string greeting = $"Hello, {firstName.ToUpper()}!";
// "Hello, JOHN!"
// With format specifiers
double price = 123.45;
string formattedPrice = $"Price: {price:C2}";
// "Price: $123.45" (culture-specific)
The $ symbol before the string indicates an interpolated string. Inside curly braces {}, you can include variables, expressions, and format specifiers.
String Methods
C# strings come with many built-in methods for manipulation and analysis:
Common String Methods:
string text = "Hello, World!";
// Length property
int length = text.Length; // 13
// Accessing characters (zero-based indexing)
char firstChar = text[0]; // 'H'
// Changing case
string lower = text.ToLower(); // "hello, world!"
string upper = text.ToUpper(); // "HELLO, WORLD!"
// Substring
string sub = text.Substring(7, 5); // "World"
// Contains, StartsWith, EndsWith
bool containsWorld = text.Contains("World"); // true
bool startsWithHello = text.StartsWith("Hello"); // true
bool endsWithExclamation = text.EndsWith("!"); // true
// IndexOf, LastIndexOf
int indexOfComma = text.IndexOf(","); // 5
int lastIndexOfL = text.LastIndexOf("l"); // 10
// Replace
string replaced = text.Replace("World", "C#"); // "Hello, C#!"
// Trim, TrimStart, TrimEnd
string paddedText = " Padded ";
string trimmed = paddedText.Trim(); // "Padded"
string trimmedStart = paddedText.TrimStart(); // "Padded "
string trimmedEnd = paddedText.TrimEnd(); // " Padded"
// Split
string csvLine = "apple,orange,banana";
string[] fruits = csvLine.Split(','); // ["apple", "orange", "banana"]
// Join
string[] words = {"Hello", "C#", "World"};
string joined = string.Join(" ", words); // "Hello C# World"
Remember that strings are immutable, so methods like Replace, ToLower, etc. don't modify the original string but return a new string with the requested changes.
String Formatting
The String.Format method provides powerful formatting capabilities:
String.Format Examples:
// Basic formatting
string formatted = string.Format("Name: {0}, Age: {1}", "John", 30);
// "Name: John, Age: 30"
// Reusing parameters
string reuse = string.Format("{0} {0} {1}", "Hello", "World");
// "Hello Hello World"
// Formatting numbers
string numberFormat = string.Format("Number: {0:N2}", 12345.6789);
// "Number: 12,345.68"
// Currency formatting
string currency = string.Format("Price: {0:C}", 123.45);
// "Price: $123.45" (culture-specific)
// Date formatting
DateTime now = DateTime.Now;
string dateFormat = string.Format("Date: {0:d}, Time: {0:t}", now);
// "Date: 5/10/2023, Time: 10:30 AM" (culture-specific)
// Padding and alignment
string leftAlign = string.Format("[{0,-10}]", "Left"); // "[Left ]"
string rightAlign = string.Format("[{0,10}]", "Right"); // "[ Right]"
Format specifiers follow a colon after the parameter index. Common format specifiers include:
C- CurrencyD- Decimal (integers)E- ExponentialF- Fixed-pointN- Number with thousand separatorsP- PercentageX- Hexadecimal
Verbatim Strings
C# provides verbatim strings which are prefixed with @ and preserve whitespace and newlines:
Verbatim String Examples:
// Regular string with escape sequences
string path = "C:\\Program Files\\dotnet\\dotnet.exe";
// Verbatim string (no need to escape backslashes)
string verbatimPath = @"C:\Program Files\dotnet\dotnet.exe";
// Multiline verbatim string
string multiline = @"This is a
multiline string
that preserves all line breaks
and whitespace.";
// Verbatim string with double quotes (use "" for a single ")
string quote = @"He said, ""Hello, World!""";
Verbatim strings are especially useful for:
- File paths (to avoid escaping backslashes)
- Regular expressions (which often contain backslashes)
- Multiline text (like SQL queries or XML/JSON data)
String Comparison
When comparing strings, it's important to use the right method to handle case sensitivity and cultural differences:
String Comparison Methods:
string str1 = "Hello";
string str2 = "hello";
// Equality operators
bool equalOperator = (str1 == str2); // false (case-sensitive)
// String.Equals
bool caseSensitive = string.Equals(str1, str2); // false
bool caseInsensitive = string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); // true
// String.Compare
int compareResult = string.Compare(str1, str2); // > 0 (str1 > str2)
int compareIgnoreCase = string.Compare(str1, str2, true); // 0 (equal when ignoring case)
// Using specific culture for comparison
int culturalComparison = string.Compare(str1, str2,
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.CompareOptions.None);
Common StringComparison options:
Ordinal- Fast, binary comparison (preferred for most comparisons)OrdinalIgnoreCase- Case-insensitive ordinal comparisonCurrentCulture- Culture-sensitive comparison (for user display)CurrentCultureIgnoreCase- Case-insensitive, culture-sensitive comparisonInvariantCulture- Culture-independent comparisonInvariantCultureIgnoreCase- Case-insensitive, culture-independent comparison
StringBuilder
For complex string manipulations, especially in loops, the StringBuilder class offers better performance than repeated string concatenation:
Using StringBuilder:
using System.Text;
// Initialize with initial string and capacity
StringBuilder sb = new StringBuilder("Initial text", 50);
// Append methods
sb.Append(" and more text");
sb.AppendLine(); // Adds a new line
sb.AppendLine("This is on a new line");
sb.AppendFormat("Formatted: {0:D3}", 42); // "Formatted: 042"
// Insert at specific position
sb.Insert(7, "modified "); // "Initial modified text..."
// Replace parts of the string
sb.Replace("text", "content");
// Remove portion of the string
sb.Remove(20, 5);
// Get the final string
string result = sb.ToString();
Benefits of StringBuilder:
- More efficient for multiple string operations
- Creates fewer temporary objects than string concatenation
- Allows direct modification of character sequences
- Can preallocate capacity for better performance
String Interpolation vs. String.Format
C# offers multiple ways to format strings. Here's a comparison:
Comparison:
// String concatenation
string concat = "Name: " + firstName + " " + lastName + ", Age: " + age;
// String.Format
string format = string.Format("Name: {0} {1}, Age: {2}", firstName, lastName, age);
// String interpolation
string interpolation = $"Name: {firstName} {lastName}, Age: {age}";
// StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("Name: ");
sb.Append(firstName);
sb.Append(" ");
sb.Append(lastName);
sb.Append(", Age: ");
sb.Append(age);
string builderResult = sb.ToString();
Guidelines for choosing the right approach:
| Method | Best Used For |
|---|---|
| String interpolation ($) | Simple formatting, readability, compile-time checking |
| String.Format | When format strings are stored separately or reused |
| Concatenation (+) | Very simple cases with few strings |
| StringBuilder | Loops, many concatenations, best performance |