.NET Strings
Introduction
Strings are one of the most fundamental data types in .NET programming. A string represents a sequence of characters and is used extensively when working with text in applications. In C#, strings are represented by the String
class in the System
namespace, though we typically use the keyword string
(lowercase) which is an alias for the String
class.
Unlike some other programming languages, strings in .NET are immutable, meaning once a string is created, its content cannot be changed. Any operation that appears to modify a string actually creates a new string instance.
Creating Strings in C#
There are several ways to create strings in C#:
String Literals
The simplest way to create a string is using string literals:
string greeting = "Hello, World!";
string emptyString = "";
String Constructor
You can also use the String
constructor:
char[] letters = { 'H', 'e', 'l', 'l', 'o' };
string greetingFromChars = new string(letters);
Console.WriteLine(greetingFromChars); // Output: Hello
string repeatedChar = new string('*', 10);
Console.WriteLine(repeatedChar); // Output: **********
String Concatenation
Strings can be combined using the +
operator:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
String Interpolation
C# offers string interpolation using the $
prefix, which allows embedding expressions directly within string literals:
string firstName = "John";
string lastName = "Doe";
int age = 30;
string bio = $"Name: {firstName} {lastName}, Age: {age}";
Console.WriteLine(bio); // Output: Name: John Doe, Age: 30
Common String Properties and Methods
Properties
string sample = "Hello, World!";
// Length - gets the number of characters
Console.WriteLine($"Length: {sample.Length}"); // Output: Length: 13
// IsNullOrEmpty - checks if string is null or empty
bool isEmpty = string.IsNullOrEmpty(sample);
Console.WriteLine($"Is empty: {isEmpty}"); // Output: Is empty: False
// IsNullOrWhiteSpace - checks if string is null, empty, or whitespace
bool isWhitespace = string.IsNullOrWhiteSpace(sample);
Console.WriteLine($"Is whitespace: {isWhitespace}"); // Output: Is whitespace: False
Methods for Searching and Comparing
string text = "The quick brown fox jumps over the lazy dog";
// Contains - checks if a substring exists
bool containsFox = text.Contains("fox");
Console.WriteLine($"Contains 'fox': {containsFox}"); // Output: Contains 'fox': True
// StartsWith and EndsWith
bool startsWithThe = text.StartsWith("The");
bool endsWithDog = text.EndsWith("dog");
Console.WriteLine($"Starts with 'The': {startsWithThe}"); // Output: Starts with 'The': True
Console.WriteLine($"Ends with 'dog': {endsWithDog}"); // Output: Ends with 'dog': True
// IndexOf - finds the position of a substring
int positionOfFox = text.IndexOf("fox");
Console.WriteLine($"Position of 'fox': {positionOfFox}"); // Output: Position of 'fox': 16
// Equals - compares strings (case-sensitive by default)
bool isEqual = "Hello".Equals("hello");
Console.WriteLine($"'Hello' equals 'hello': {isEqual}"); // Output: 'Hello' equals 'hello': False
// Case-insensitive comparison
bool isEqualIgnoreCase = "Hello".Equals("hello", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"'Hello' equals 'hello' (ignore case): {isEqualIgnoreCase}"); // Output: 'Hello' equals 'hello' (ignore case): True
Methods for Modifying Strings
Remember, strings are immutable, so these methods return new string instances:
string original = " Hello, World! ";
// Trim - removes whitespace from start and end
string trimmed = original.Trim();
Console.WriteLine($"Trimmed: '{trimmed}'"); // Output: Trimmed: 'Hello, World!'
// Replace - replaces all occurrences of a character/string
string replaced = trimmed.Replace("World", "C# Developer");
Console.WriteLine($"Replaced: {replaced}"); // Output: Replaced: Hello, C# Developer!
// ToUpper and ToLower
string uppercase = replaced.ToUpper();
string lowercase = replaced.ToLower();
Console.WriteLine($"Uppercase: {uppercase}"); // Output: Uppercase: HELLO, C# DEVELOPER!
Console.WriteLine($"Lowercase: {lowercase}"); // Output: Lowercase: hello, c# developer!
// Substring - extracts a portion of string
string substring = replaced.Substring(7, 12); // Start at index 7, take 12 characters
Console.WriteLine($"Substring: {substring}"); // Output: Substring: C# Developer
// Split - divides a string into substrings based on delimiters
string sentence = "C# is a powerful programming language";
string[] words = sentence.Split(' ');
Console.WriteLine("Words in sentence:");
foreach (var word in words)
{
Console.WriteLine(word);
}
/*
Output:
Words in sentence:
C#
is
a
powerful
programming
language
*/
// Join - combines an array of strings into one string
string joined = string.Join("-", words);
Console.WriteLine($"Joined: {joined}"); // Output: Joined: C#-is-a-powerful-programming-language
String Building and Performance
When you need to perform many string operations, using the +
operator can create performance issues due to the immutability of strings. For these scenarios, .NET provides the StringBuilder
class:
using System.Text;
StringBuilder builder = new StringBuilder();
builder.Append("Hello");
builder.Append(", ");
builder.Append("World!");
builder.AppendLine(); // Adds a line break
builder.AppendFormat("The time is {0:t} on {0:d}", DateTime.Now);
string result = builder.ToString();
Console.WriteLine(result);
/*
Output example:
Hello, World!
The time is 3:45 PM on 7/20/2023
*/
String Formatting
.NET offers powerful string formatting capabilities:
Composite Formatting
string formatted = string.Format("Name: {0}, Age: {1}", "Alice", 25);
Console.WriteLine(formatted); // Output: Name: Alice, Age: 25
// With format specifiers
decimal price = 1234.5678m;
string formattedPrice = string.Format("Price: {0:C}", price);
Console.WriteLine(formattedPrice); // Output: Price: $1,234.57 (format depends on culture)
// Date formatting
DateTime now = DateTime.Now;
string formattedDate = string.Format("Date: {0:yyyy-MM-dd}", now);
Console.WriteLine(formattedDate); // Output: Date: 2023-07-20 (example date)
Common Format Specifiers
decimal value = 1234.5678m;
Console.WriteLine($"Currency: {value:C}"); // Output: $1,234.57
Console.WriteLine($"Number: {value:N2}"); // Output: 1,234.57
Console.WriteLine($"Percentage: {value:P1}"); // Output: 123,456.8%
Console.WriteLine($"Scientific: {value:E2}"); // Output: 1.23E+003
Console.WriteLine($"Fixed-point: {value:F1}"); // Output: 1234.6
Real-World Applications
Creating a User Profile Generator
public class UserProfile
{
public string GenerateProfile(string name, int age, string[] hobbies)
{
StringBuilder profile = new StringBuilder();
profile.AppendLine($"User Profile: {name}");
profile.AppendLine($"Age: {age}");
profile.AppendLine("Hobbies:");
for (int i = 0; i < hobbies.Length; i++)
{
profile.AppendLine($" {i+1}. {hobbies[i]}");
}
profile.AppendLine($"Profile Generated on: {DateTime.Now:F}");
return profile.ToString();
}
}
// Usage
UserProfile profileGenerator = new UserProfile();
string profile = profileGenerator.GenerateProfile(
"Jane Smith",
28,
new string[] { "Reading", "Hiking", "Photography" }
);
Console.WriteLine(profile);
/*
Output example:
User Profile: Jane Smith
Age: 28
Hobbies:
1. Reading
2. Hiking
3. Photography
Profile Generated on: Thursday, July 20, 2023 3:45:30 PM
*/
Text Processing Example
public class TextAnalyzer
{
public void AnalyzeText(string text)
{
// Convert to lowercase for case-insensitive analysis
string lowerText = text.ToLower();
// Count words
string[] words = lowerText.Split(new char[] { ' ', '.', ',', '!', '?', ':', ';', '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
// Count sentences (simplified)
string[] sentences = text.Split(new char[] { '.', '!', '?' },
StringSplitOptions.RemoveEmptyEntries);
int sentenceCount = sentences.Length;
// Find most common word
var wordFrequency = new Dictionary<string, int>();
foreach (string word in words)
{
if (wordFrequency.ContainsKey(word))
wordFrequency[word]++;
else
wordFrequency[word] = 1;
}
string mostCommonWord = wordFrequency.OrderByDescending(pair => pair.Value)
.First().Key;
// Print results
Console.WriteLine($"Text Analysis Results:");
Console.WriteLine($"Word count: {wordCount}");
Console.WriteLine($"Sentence count: {sentenceCount}");
Console.WriteLine($"Most common word: '{mostCommonWord}'");
}
}
// Usage
string sampleText = "The quick brown fox jumps over the lazy dog. The fox was very quick. The dog was very lazy.";
TextAnalyzer analyzer = new TextAnalyzer();
analyzer.AnalyzeText(sampleText);
/*
Output:
Text Analysis Results:
Word count: 19
Sentence count: 3
Most common word: 'the'
*/
Best Practices for Working with Strings
- Use string interpolation (
$"..."
) for readable string formatting - Use
StringBuilder
for intensive string concatenation operations - Be mindful of culture-specific operations when formatting numbers, dates, etc.
- Use string comparison methods properly with appropriate
StringComparison
options - Avoid unnecessary string allocations by reusing strings when possible
- Consider using
string.Empty
instead of""
for empty strings (more readable) - Use string.IsNullOrEmpty/IsNullOrWhiteSpace for validation rather than checking manually
Summary
In this guide, we've explored .NET strings in depth:
- Strings in .NET are immutable sequences of characters
- String creation using literals, constructors, and concatenation
- String properties and methods for searching, comparing, and modifying
- Performance considerations using
StringBuilder
- Powerful formatting options with format specifiers
- Real-world applications for string manipulation
Strings are fundamental to almost every application, from simple console programs to complex web applications. Understanding how to work with them efficiently is a core skill for any .NET developer.
Additional Resources
- Microsoft Documentation: String Class
- Microsoft Documentation: StringBuilder Class
- C# String Formatting Guide
Exercises
- Create a program that reverses each word in a sentence while maintaining word order.
- Write a function that counts the occurrences of each character in a string.
- Implement a simple text-based menu system using string formatting.
- Create a CSV parser that converts a string into a list of records.
- Build a simple template engine that replaces placeholders in a template string with actual values.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)