C# String Manipulation Methods Every Developer Should Know
Strings are used throughout C# applications for names, messages, file paths, user input, API data, and many other tasks. C# provides a wide range of methods for searching, modifying, comparing, and formatting text.
What is a String in C#?
A string is a sequence of characters represented by the System.String type. Strings in C# are immutable, which means operations that appear to modify a string actually create a new string value.
string name = "Codecrown";
Console.WriteLine(name);
String Length
The Length property returns the number of characters contained in a string.
string text = "Hello C#";
Console.WriteLine(text.Length);
Changing Letter Case
ToUpper and ToLower can be used when you need to convert text to uppercase or lowercase.
string text = "Hello World";
Console.WriteLine(text.ToUpper());
Console.WriteLine(text.ToLower());
Removing Extra Spaces
Trim removes whitespace from the beginning and end of a string. TrimStart and TrimEnd can be used when only one side needs to be cleaned.
string input = " Hello C# ";
string clean = input.Trim();
Console.WriteLine(clean);
Searching Inside a String
Methods such as Contains, StartsWith, EndsWith, and IndexOf help determine whether specific text exists inside a string.
string email = "user@example.com";
bool hasAt = email.Contains("@");
bool startsWithUser = email.StartsWith("user");
int position = email.IndexOf("@");
Replacing Text
Replace creates a new string with matching text replaced by another value.
string message = "Welcome to Java";
string updated = message.Replace("Java", "C#");
Console.WriteLine(updated);
Splitting a String
Split separates a string into multiple parts based on one or more separators.
string data = "C#,Java,Python";
string[] languages = data.Split(',');
foreach (string language in languages)
{
Console.WriteLine(language);
}
Joining Strings
String.Join combines multiple values into a single string using a specified separator.
string[] languages = { "C#", "Java", "Python" };
string result = string.Join(", ", languages);
Console.WriteLine(result);
String Interpolation
String interpolation provides a convenient way to insert variables and expressions directly into a string.
string name = "Alice";
int age = 25;
string message = $"My name is {name} and I am {age} years old.";
Console.WriteLine(message);
Comparing Strings
String.Equals and string comparison methods can be used when applications need to determine whether two strings have the same value.
string first = "hello";
string second = "HELLO";
bool same = string.Equals(
first,
second,
StringComparison.OrdinalIgnoreCase
);
Console.WriteLine(same);
Substring
Substring extracts part of a string based on a starting position and, optionally, a length.
string text = "Hello World";
string part = text.Substring(0, 5);
Console.WriteLine(part);
Common String Methods
| Method | Purpose | Example |
|---|---|---|
| Length | Get character count | text.Length |
| Contains | Check for text | text.Contains("C#") |
| Replace | Replace text | text.Replace("A", "B") |
| Split | Divide text | text.Split(',') |
| Trim | Remove surrounding whitespace | text.Trim() |
| Substring | Extract part of text | text.Substring(0, 5) |
| ToUpper | Convert to uppercase | text.ToUpper() |
StringBuilder in C#
StringBuilder is useful when an application needs to perform many string modifications. Unlike regular strings, it can modify its internal character buffer without creating a new string for every operation.
using System.Text;
StringBuilder builder = new StringBuilder();
builder.Append("Hello");
builder.Append(" ");
builder.Append("C#");
Console.WriteLine(builder.ToString());
String vs StringBuilder
| Feature | string | StringBuilder |
|---|---|---|
| Mutability | Immutable | Mutable |
| Simple Text | Excellent choice | Usually unnecessary |
| Many Modifications | Can create many intermediate strings | Designed for repeated modifications |
| Namespace | System | System.Text |
Real-World Applications
- Processing user input
- Building API responses
- Generating reports
- Parsing CSV or text data
- Formatting application messages
- Creating file contents
- Cleaning imported data
Common Mistakes to Avoid
- Forgetting that strings are immutable
- Using excessive string concatenation in large loops
- Comparing user input without considering case requirements
- Assuming Trim removes every type of unwanted character
- Using culture-sensitive comparisons when ordinal comparison is required
Advanced String Concepts
- Raw string literals
- String interpolation
- StringBuilder
- Span
- Culture-aware comparisons
- Regular expressions
- UTF-16 and Unicode
Practice Exercises
- Count the characters in a sentence
- Reverse a string
- Count vowels in a word
- Replace specific words in a paragraph
- Split a comma-separated list
- Build a formatted message using interpolation
- Create a large text using StringBuilder
Conclusion
String manipulation is a fundamental skill for C# developers. By understanding common methods, interpolation, comparisons, and StringBuilder, you can process text more effectively and write cleaner applications.