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.

CSHARP
string name = "Codecrown";
Console.WriteLine(name);

String Length

The Length property returns the number of characters contained in a string.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
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.

CSHARP
string text = "Hello World";

string part = text.Substring(0, 5);

Console.WriteLine(part);

Common String Methods

MethodPurposeExample
LengthGet character counttext.Length
ContainsCheck for texttext.Contains("C#")
ReplaceReplace texttext.Replace("A", "B")
SplitDivide texttext.Split(',')
TrimRemove surrounding whitespacetext.Trim()
SubstringExtract part of texttext.Substring(0, 5)
ToUpperConvert to uppercasetext.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.

CSHARP
using System.Text;

StringBuilder builder = new StringBuilder();

builder.Append("Hello");
builder.Append(" ");
builder.Append("C#");

Console.WriteLine(builder.ToString());

String vs StringBuilder

FeaturestringStringBuilder
MutabilityImmutableMutable
Simple TextExcellent choiceUsually unnecessary
Many ModificationsCan create many intermediate stringsDesigned for repeated modifications
NamespaceSystemSystem.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.

Note: Note: Use normal strings for simple text operations and consider StringBuilder when repeatedly modifying large or frequently changing text.