C# String Functions: A Practical Guide

Formulas & functions · Updated November 22, 2026

C# string functions are methods and properties on the built-in string type, also called System.String. Common choices include Length for the number of UTF-16 code units, Contains and IndexOf for searching, Substring for extracting text, and Replace, Split, and Trim for transformations.

What C# string functions mean

In C#, string is an alias for the .NET System.String reference type. It represents a sequence of UTF-16 code units. You can call instance methods on a string value, such as text.ToUpper(), or static methods on the type, such as String.Join. The modern lowercase spelling, string, is conventional in C# code; both spellings refer to the same type.

Strings are immutable: a method that appears to change text actually returns a new string, leaving the original value unchanged. For example, text.Replace("cat", "dog") produces a result; it does not edit text in place. Store or use the returned value if you need the transformed text. This is an important difference from mutable collections and a frequent source of bugs for new C# programmers.

There is no single function called “string functions.” The useful API is a collection of methods for inspecting, searching, comparing, formatting, splitting, and converting text. The right choice depends on the task and, for comparisons, sometimes on the language and culture of the text.

Core properties and simple operations

Length is a property, not a method, and returns the number of UTF-16 code units in a string. For ordinary English letters this usually matches the number of visible characters, but some Unicode symbols use more than one code unit. As a result, Length is not always the count a person would consider the number of characters.

String concatenation with + is straightforward for a few values. Interpolation, written with a dollar sign before a string, is often clearer when inserting values into a sentence:

string name = "Mina";
int items = 3;
string message = $"{name} has {items} items.";

Other basic tools include IsNullOrEmpty, which is true for a null reference or an empty string, and IsNullOrWhiteSpace, which also treats strings made only of whitespace as empty. These are static methods, so call them as string.IsNullOrWhiteSpace(value). They are useful when checking optional input before processing it.

Searching within text

Use Contains when you only need to know whether a substring occurs. Use IndexOf when you also need its position: it returns a zero-based index, or -1 when no match exists. StartsWith and EndsWith check the beginning and end of a string. These methods can take a StringComparison option to make the matching rule explicit.

string fileName = "Report.CSV";
bool hasCsv = fileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase);
int comma = "red,green,blue".IndexOf(',');

Here, hasCsv is true, because the suffix check ignores case, and comma is 3, because the first comma is at index three. For user-facing language text, culture-sensitive searching may be appropriate; for identifiers, protocol tokens, file extensions, and other machine-oriented values, ordinal comparison is usually more predictable. Avoid assuming that every string search is automatically case-insensitive: the default behavior of common overloads is case-sensitive.

Changing, trimming, and extracting strings

Replace returns a string with matching text or characters replaced. ToUpper and ToLower change letter casing, while Trim, TrimStart, and TrimEnd remove whitespace from both ends, the beginning, or the end. These methods do not remove whitespace from the middle of a string. For machine-readable text, casing methods can accept a culture; ToUpperInvariant and ToLowerInvariant use culture-independent casing rules.

Substring extracts part of a string by index and length. Its starting index is zero-based, and invalid ranges can throw an exception. The range syntax, such as text[1..4], is another concise way to select a section in modern C#:

string input = "  blue sky  ";
string clean = input.Trim();
string firstFour = clean.Substring(0, 4);
string replaced = clean.Replace("blue", "gray");

After trimming, clean is "blue sky"; firstFour is "blue", and replaced is "gray sky". If a substring may not exist or its length is uncertain, check the relevant indexes and lengths before calling Substring, or use a search-and-parse method that handles missing data explicitly.

Comparing strings correctly

String equality and ordering are not always just a matter of uppercase versus lowercase. A culture-aware comparison follows language-specific conventions, while an ordinal comparison compares the underlying text values without linguistic interpretation. For machine identifiers and many internal checks, use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase. For text intended for people, select a culture-aware comparison when the desired behavior depends on the user’s language.

For example, Equals can compare two strings with an explicit rule, and Compare provides ordering information. Avoid converting both values to uppercase or lowercase just to compare them; a comparison overload expresses the intent directly and avoids creating temporary strings. Also note that == on strings compares their contents, not whether the variables refer to the same object.

Comparison rules matter in sorting, searching, and security-sensitive checks. A culture-based rule that is suitable for a display name may be unsuitable for a protocol keyword or account identifier. Choose the rule based on what the value represents rather than applying one rule to every string.

Formatting values into text

String interpolation is a readable way to combine text with values: $"Order {orderId}: {total:C}" inserts values and supports format specifiers. The C format displays a number as currency according to the current culture, so the symbol and formatting can vary by environment. For a fixed culture, use formatting APIs that accept an explicit culture rather than relying on the machine’s defaults.

String.Format is another option, especially when a format template is stored separately or when working with APIs that use numbered placeholders. String.Join combines a sequence of values with a separator. For example, string.Join(", ", new[] { "red", "green", "blue" }) returns "red, green, blue". Prefer it to manually adding a separator between each item, which can lead to extra commas or spaces.

Formatting is for producing text, not for validating or parsing it. If a value must be converted back into a number or date, use an appropriate parsing method and specify culture where the input format requires it.

Splitting and joining text

Split divides a string around one or more separators and returns an array of strings. For example, "red,green,blue".Split(',') produces three elements. A common issue is that separators may create empty entries: "red,,blue" contains an empty item between the commas. Some overloads let you remove empty entries or trim whitespace, but be clear about whether empty fields are meaningful in your data.

For simple, predictable formats, Split is convenient. It is not a complete parser for formats with quoting or escaping. A comma-separated file can contain commas inside quoted fields, for example, so splitting every line on commas can misread valid data. Use a CSV parser for CSV files instead of treating them as plain delimited text.

To build text from pieces, String.Join accepts an array or other sequence and inserts the separator between elements. When splitting user input, consider trimming each item if spaces around separators should be ignored. Do that deliberately: whitespace may be significant in some data formats.

Checking and converting input

Strings often arrive from a user, a file, or a network request, so do not assume that text contains a valid number or date. Methods such as int.Parse and DateTime.Parse convert valid text but can throw exceptions when the input is invalid or uses an unexpected format. For routine validation, TryParse is generally more convenient because it reports success as a Boolean and provides the converted result through an output parameter.

string input = "42";
if (int.TryParse(input, out int number))
{
    Console.WriteLine(number + 1);
}

With this input, parsing succeeds and the program prints 43. For dates or numbers that must follow a particular format, use overloads that accept a format provider or parsing styles. For example, a date written as month/day/year can be ambiguous across countries; relying on the computer’s current culture can interpret it differently than intended.

Validation should match the actual requirement. A check that a string is nonempty does not prove it is a valid email address, identifier, or date. Apply format-specific validation when needed, and distinguish a failed conversion from a valid value such as zero.

Performance and common mistakes

Because strings are immutable, repeated concatenation inside a large loop can create many intermediate strings. For a small fixed number of values, interpolation or + is clear and appropriate. For building a large result incrementally, StringBuilder is often a better fit because it can append multiple pieces before producing the final string.

  • Remember to assign the result of methods such as Replace, Trim, and ToUpper; they do not modify the original string.
  • Check for null before calling an instance method, or use a suitable static helper such as string.IsNullOrWhiteSpace.
  • Use IndexOf results only after checking for -1, and verify substring ranges before extracting text.
  • Choose an explicit comparison rule when case sensitivity or culture could change the result.
  • Do not treat Length as a guaranteed count of visible Unicode characters.

For text elements that a user perceives as single characters, including some emoji and combined accents, Unicode grapheme clusters are more relevant than UTF-16 code units. .NET provides text-element enumeration through StringInfo for cases that need this distinction. Most basic data-processing code can use normal string methods, but user interfaces that count or select visible characters may need Unicode-aware handling.

Frequently Asked Questions

How do I find a word in a C# string?
Use Contains to get a true-or-false answer, or IndexOf to find the position. Choose an overload with StringComparison if the search needs a specific case or culture rule.

How do I make a C# string lowercase?
Call ToLower() for casing based on the current culture, or ToLowerInvariant() for culture-independent casing. Both return a new string; neither changes the original value.

What is the difference between Trim and Replace?
Trim removes whitespace at the beginning and end of a string. Replace substitutes matching characters or text wherever they occur, so it can also affect the middle of a string.

How can I check whether a string is empty or null?
Use string.IsNullOrEmpty(value) to check for null or an empty string. Use string.IsNullOrWhiteSpace(value) when whitespace-only input should count as empty too.

Does C# have a string length function?
Use the Length property, written as text.Length, not a function call. It counts UTF-16 code units, which may differ from the number of visible Unicode characters.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.