C# String Methods
Introduction
Strings in C# are fundamental data types used to represent text. They are immutable objects, meaning once created, their content cannot be changed. However, C# provides a rich set of methods that allow you to manipulate strings in various ways, creating new string objects with the desired modifications.
In this tutorial, we'll explore the most commonly used string methods in C# that will help you manipulate text effectively in your programs.
Basic String Operations
Length Property
Before diving into methods, let's look at the most basic property of strings - the Length
property.
string greeting = "Hello, World!";
int length = greeting.Length;
Console.WriteLine($"The length of the string is: {length}");
// Output:
// The length of the string is: 13
Accessing Characters
You can access individual characters in a string using indexing:
string text = "C# Programming";
char firstChar = text[0]; // 'C'
char fifthChar = text[4]; // 'r'
Console.WriteLine($"First character: {firstChar}");
Console.WriteLine($"Fifth character: {fifthChar}");
// Output:
// First character: C
// Fifth character: r
String Transformation Methods
ToUpper() and ToLower()
These methods convert a string to uppercase or lowercase:
string original = "Hello World";
string upperCase = original.ToUpper();
string lowerCase = original.ToLower();
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Uppercase: {upperCase}");
Console.WriteLine($"Lowercase: {lowerCase}");
// Output:
// Original: Hello World
// Uppercase: HELLO WORLD
// Lowercase: hello world
Trim(), TrimStart(), TrimEnd()
These methods remove whitespace from strings:
string textWithSpaces = " Hello World ";
string trimmed = textWithSpaces.Trim();
string trimStart = textWithSpaces.TrimStart();
string trimEnd = textWithSpaces.TrimEnd();
Console.WriteLine($"Original: '{textWithSpaces}'");
Console.WriteLine($"Trimmed: '{trimmed}'");
Console.WriteLine($"Trim Start: '{trimStart}'");
Console.WriteLine($"Trim End: '{trimEnd}'");
// Output:
// Original: ' Hello World '
// Trimmed: 'Hello World'
// Trim Start: 'Hello World '
// Trim End: ' Hello World'
You can also specify which characters to trim:
string text = "***Hello World***";
string trimmedStars = text.Trim('*');
Console.WriteLine($"Original: '{text}'");
Console.WriteLine($"Trimmed Stars: '{trimmedStars}'");
// Output:
// Original: '***Hello World***'
// Trimmed Stars: 'Hello World'
PadLeft() and PadRight()
These methods add padding to make strings a specific length:
string number = "42";
string padded = number.PadLeft(5, '0');
string paddedRight = number.PadRight(5, '-');
Console.WriteLine($"Original: '{number}'");
Console.WriteLine($"Padded Left: '{padded}'");
Console.WriteLine($"Padded Right: '{paddedRight}'");
// Output:
// Original: '42'
// Padded Left: '00042'
// Padded Right: '42---'
Replace()
This method replaces occurrences of a character or substring with another:
string sentence = "I like apples and apples are my favorite fruit.";
string replaced = sentence.Replace("apples", "oranges");
Console.WriteLine($"Original: {sentence}");
Console.WriteLine($"Replaced: {replaced}");
// Output:
// Original: I like apples and apples are my favorite fruit.
// Replaced: I like oranges and oranges are my favorite fruit.
String Searching Methods
Contains()
Checks if a string contains a specific substring:
string sentence = "The quick brown fox jumps over the lazy dog.";
bool containsFox = sentence.Contains("fox");
bool containsCat = sentence.Contains("cat");
Console.WriteLine($"Contains 'fox': {containsFox}");
Console.WriteLine($"Contains 'cat': {containsCat}");
// Output:
// Contains 'fox': True
// Contains 'cat': False
StartsWith() and EndsWith()
Check if a string starts or ends with a specific substring:
string email = "[email protected]";
bool startsWithUser = email.StartsWith("user");
bool endsWithCom = email.EndsWith(".com");
Console.WriteLine($"Starts with 'user': {startsWithUser}");
Console.WriteLine($"Ends with '.com': {endsWithCom}");
// Output:
// Starts with 'user': True
// Ends with '.com': True
IndexOf() and LastIndexOf()
Find the position of a substring within a string:
string sentence = "The quick brown fox jumps over the lazy dog.";
int firstThe = sentence.IndexOf("the");
int lastThe = sentence.LastIndexOf("the");
Console.WriteLine($"First occurrence of 'the': {firstThe}");
Console.WriteLine($"Last occurrence of 'the': {lastThe}");
// Output:
// First occurrence of 'the': 0
// Last occurrence of 'the': 31
Note that IndexOf()
is case-sensitive. To perform case-insensitive searches, you can convert both strings to the same case:
string sentence = "The quick brown fox jumps over the lazy dog.";
int firstThe = sentence.ToLower().IndexOf("the");
Console.WriteLine($"First occurrence of 'the' (case-insensitive): {firstThe}");
// Output:
// First occurrence of 'the' (case-insensitive): 0
String Extraction Methods
Substring()
Extracts a portion of a string:
string sentence = "The quick brown fox jumps over the lazy dog.";
string substring = sentence.Substring(4, 5); // Start at index 4, take 5 characters
string toEnd = sentence.Substring(10); // Start at index 10, take all remaining characters
Console.WriteLine($"Substring(4, 5): '{substring}'");
Console.WriteLine($"Substring(10): '{toEnd}'");
// Output:
// Substring(4, 5): 'quick'
// Substring(10): 'brown fox jumps over the lazy dog.'
String Splitting and Joining
Split()
Splits a string into an array of substrings based on a delimiter:
string csvData = "John,Doe,30,New York";
string[] parts = csvData.Split(',');
Console.WriteLine("Split result:");
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine($" Part {i}: {parts[i]}");
}
// Output:
// Split result:
// Part 0: John
// Part 1: Doe
// Part 2: 30
// Part 3: New York
You can also specify multiple delimiters:
string data = "apple;banana,orange grape|pear";
char[] delimiters = {';', ',', ' ', '|'};
string[] fruits = data.Split(delimiters);
Console.WriteLine("Fruits:");
foreach (string fruit in fruits)
{
Console.WriteLine($" {fruit}");
}
// Output:
// Fruits:
// apple
// banana
// orange
// grape
// pear
Join()
The static String.Join()
method combines an array of strings into a single string with a specified separator:
string[] words = {"Hello", "World", "of", "C#"};
string joined = String.Join(" ", words);
string joinedWithComma = String.Join(", ", words);
Console.WriteLine($"Joined with spaces: '{joined}'");
Console.WriteLine($"Joined with commas: '{joinedWithComma}'");
// Output:
// Joined with spaces: 'Hello World of C#'
// Joined with commas: 'Hello, World, of, C#'
String Formatting and Interpolation
Format()
The static String.Format()
method formats a string using placeholders:
string name = "Alice";
int age = 30;
string formattedString = String.Format("My name is {0} and I am {1} years old.", name, age);
Console.WriteLine(formattedString);
// Output:
// My name is Alice and I am 30 years old.
String Interpolation
C# 6.0 introduced string interpolation, which provides a more readable way to create formatted strings:
string name = "Bob";
int age = 25;
string interpolatedString = $"My name is {name} and I am {age} years old.";
Console.WriteLine(interpolatedString);
// Output:
// My name is Bob and I am 25 years old.
Real-World Applications
Example 1: Validating User Input
public static bool IsValidEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
email = email.Trim();
// Basic check: contains @ and has characters before and after it
int atIndex = email.IndexOf('@');
if (atIndex <= 0 || atIndex == email.Length - 1)
return false;
// Check for dots after @ character
string domain = email.Substring(atIndex + 1);
if (!domain.Contains(".") || domain.EndsWith("."))
return false;
return true;
}
// Usage:
string email1 = "[email protected]";
string email2 = "invalid@email";
string email3 = "@nousername.com";
Console.WriteLine($"Is '{email1}' valid? {IsValidEmail(email1)}");
Console.WriteLine($"Is '{email2}' valid? {IsValidEmail(email2)}");
Console.WriteLine($"Is '{email3}' valid? {IsValidEmail(email3)}");
// Output:
// Is '[email protected]' valid? True
// Is 'invalid@email' valid? False
// Is '@nousername.com' valid? False
Example 2: Parsing CSV Data
public static void ParseCsvLine(string csvLine)
{
string[] values = csvLine.Split(',');
if (values.Length < 3)
{
Console.WriteLine("Invalid CSV format");
return;
}
string name = values[0].Trim();
string email = values[1].Trim();
int age;
bool isAgeValid = int.TryParse(values[2].Trim(), out age);
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Email: {email}");
Console.WriteLine($"Age: {(isAgeValid ? age.ToString() : "Invalid")}");
}
// Usage:
string csvLine = "John Doe, [email protected], 30";
ParseCsvLine(csvLine);
// Output:
// Name: John Doe
// Email: [email protected]
// Age: 30
Example 3: Text Processing
public static void CountWords(string text)
{
if (string.IsNullOrWhiteSpace(text))
{
Console.WriteLine("Empty text");
return;
}
// Remove punctuation and convert to lowercase
string cleanText = text
.ToLower()
.Replace(".", "")
.Replace(",", "")
.Replace("!", "")
.Replace("?", "");
// Split into words
string[] words = cleanText.Split(new char[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);
// Count word frequency
Dictionary<string, int> wordFrequency = new Dictionary<string, int>();
foreach (string word in words)
{
if (wordFrequency.ContainsKey(word))
wordFrequency[word]++;
else
wordFrequency[word] = 1;
}
// Display results
Console.WriteLine($"Total words: {words.Length}");
Console.WriteLine("Word frequency (top 5):");
var topWords = wordFrequency
.OrderByDescending(pair => pair.Value)
.Take(5);
foreach (var pair in topWords)
{
Console.WriteLine($" {pair.Key}: {pair.Value}");
}
}
// Usage:
string sampleText = "The quick brown fox jumps over the lazy dog. The dog was not very lazy after all!";
CountWords(sampleText);
// Output:
// Total words: 16
// Word frequency (top 5):
// the: 3
// lazy: 2
// dog: 2
// quick: 1
// brown: 1
Summary
In this lesson, we've covered many of the essential string methods in C# that you'll use frequently in your programming journey:
- Basic string properties like
Length
- Transformation methods like
ToUpper()
,ToLower()
,Trim()
, andReplace()
- Searching methods like
Contains()
,StartsWith()
,EndsWith()
, andIndexOf()
- Extraction methods like
Substring()
- Splitting and joining with
Split()
andJoin()
- Formatting strings using
String.Format()
and string interpolation
Remember that strings in C# are immutable, which means these methods don't modify the original string but instead return a new string. This immutability helps prevent unexpected side effects in your code.
Practice Exercises
- Name Formatter: Write a program that takes a full name (first and last) as input and formats it to "Last, First".
- URL Parser: Create a function that extracts the domain name from a URL (e.g., from "https://www.example.com/page" extract "example.com").
- Password Validator: Write a function that checks if a password meets these criteria: at least 8 characters, contains uppercase, lowercase, and a number.
- Text Analyzer: Create a program that counts the number of vowels and consonants in a text.
- CSV Parser: Build a more comprehensive CSV parser that can handle quoted fields (e.g., fields that contain commas within quotes).
Additional Resources
- Microsoft Documentation on String Methods
- C# String Formatting Guide
- Regular Expressions in C# - for more advanced text processing
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)