Table of Contents

StringExtensions Class

Definition

Namespace
Bodu.Extensions
Assembly
Bodu.Core.dll
Package
Bodu.Core 1.0.1
Source
StringExtensions.After.cs

Provides ergonomic, allocation-aware extension methods on string that fill gaps in the BCL - positive-form null/empty predicates, fluent fallbacks, whitespace and line-ending normalisation, affix management, substring windowing, case conversion, identifier sanitisation, and generic parsing.

public static class StringExtensions
Inheritance
StringExtensions
Inherited Members

Examples

// Sanitise then truncate user input for a log line.
string? raw = request?.Title;
string display = raw.TrimToNull()?.CollapseWhitespace().Truncate(80, "…") ?? "(untitled)";

// Build a slug for a URL.
string slug = "Hello, World! - café".ToSlug();   // "hello-world-cafe"

// Round-trip identifiers between conventions.
string pascal = "user_account_id".ToPascalCase(); // "UserAccountId"
string snake  = "UserAccountId".ToSnakeCase();    // "user_account_id"

Remarks

Members are split across partial files following the repository convention (see CLAUDE.md): one partial file per method, named StringExtensions.<MethodName>.cs. Tests follow the same pattern under test/Extensions/StringExtensionsTests.<MethodName>.cs.

Methods that conceptually deserve a place but are already short, idiomatic, or covered by the BCL are intentionally omitted (for example IsNullOrEmpty, Left / Right, Mid, ToLowerInvariant). The accompanying design document records the rationale per method.

Casing methods use InvariantCulture by default so output is deterministic across machines; cultural variants are not provided to discourage accidental CurrentCulture coupling. Comparison helpers default to Ordinal for the same reason.

Methods

After(string, string, StringComparison)

Returns the substring of value following the first occurrence of marker.

public static string? After(this string value, string marker, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

marker string

The marker to locate. Must not be null.

comparison StringComparison

The comparison rule used to locate marker. Defaults to Ordinal.

Returns

string

The characters after the first occurrence of marker, or null when marker is not found.

Examples

"user@example.com".After("@");  // "example.com"
"no-delimiter".After("@");      // null

Exceptions

ArgumentNullException

Thrown when value or marker is null.

AfterLast(string, string, StringComparison)

Returns the substring of value following the last occurrence of marker.

public static string? AfterLast(this string value, string marker, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

marker string

The marker to locate. Must not be null.

comparison StringComparison

The comparison rule used to locate marker. Defaults to Ordinal.

Returns

string

The characters after the last occurrence of marker, or null when marker is not found.

Exceptions

ArgumentNullException

Thrown when value or marker is null.

Before(string, string, StringComparison)

Returns the substring of value preceding the first occurrence of marker.

public static string? Before(this string value, string marker, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

marker string

The marker to locate. Must not be null.

comparison StringComparison

The comparison rule used to locate marker. Defaults to Ordinal.

Returns

string

The characters before the first occurrence of marker, or null when marker is not found.

Exceptions

ArgumentNullException

Thrown when value or marker is null.

BeforeLast(string, string, StringComparison)

Returns the substring of value preceding the last occurrence of marker.

public static string? BeforeLast(this string value, string marker, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

marker string

The marker to locate. Must not be null.

comparison StringComparison

The comparison rule used to locate marker. Defaults to Ordinal.

Returns

string

The characters before the last occurrence of marker, or null when marker is not found.

Exceptions

ArgumentNullException

Thrown when value or marker is null.

Between(string, string, string, StringComparison)

Returns the substring of value between the first occurrence of start and the next occurrence of end after it.

public static string? Between(this string value, string start, string end, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

start string

The opening marker. Must not be null.

end string

The closing marker. Must not be null.

comparison StringComparison

The comparison rule used to locate the markers. Defaults to Ordinal.

Returns

string

The substring between the markers, or null when either marker is not present in the expected order.

Exceptions

ArgumentNullException

Thrown when value, start, or end is null.

Brace(string)

Returns value wrapped in curly-brace characters ({…}).

public static string Brace(this string value)

Parameters

value string

The string to wrap. Must not be null.

Returns

string

The braced string.

Exceptions

ArgumentNullException

Thrown when value is null.

Bracket(string)

Returns value wrapped in square-bracket characters ([…]).

public static string Bracket(this string value)

Parameters

value string

The string to wrap. Must not be null.

Returns

string

The bracketed string.

Exceptions

ArgumentNullException

Thrown when value is null.

CollapseWhitespace(string)

Returns value with every run of one or more white-space characters collapsed to a single space character (U+0020).

public static string CollapseWhitespace(this string value)

Parameters

value string

The string to collapse. Must not be null.

Returns

string

A new string where consecutive white-space characters have been replaced by a single space. When value contains no runs of two or more white-space characters and no non-space white-space characters, the original value is returned unchanged.

Remarks

Leading and trailing white-space is collapsed but not removed. Combine with Trim() to also strip the edges. White-space is detected via IsWhiteSpace(char) so Unicode separators (NBSP, EN SPACE, line terminators, tab) all collapse to a single ASCII space.

Exceptions

ArgumentNullException

Thrown when value is null.

ContainsOrdinalIgnoreCase(string, string)

Returns a value indicating whether value contains valueToFind under OrdinalIgnoreCase.

public static bool ContainsOrdinalIgnoreCase(this string value, string valueToFind)

Parameters

value string

The string to search. Must not be null.

valueToFind string

The substring to locate. Must not be null.

Returns

bool

true when valueToFind occurs at least once within value under case-insensitive ordinal comparison; otherwise false.

Exceptions

ArgumentNullException

Thrown when value or valueToFind is null.

DefaultIfNullOrEmpty(string?, string)

Returns defaultValue when value is null or empty; otherwise returns value unchanged.

public static string DefaultIfNullOrEmpty(this string? value, string defaultValue)

Parameters

value string

The string to evaluate.

defaultValue string

The fallback returned when value is null or empty. Must not be null.

Returns

string

value when it contains at least one character; otherwise defaultValue.

Exceptions

ArgumentNullException

Thrown when defaultValue is null.

DefaultIfNullOrWhiteSpace(string?, string)

Returns defaultValue when value is null, empty, or white-space-only; otherwise returns value unchanged.

public static string DefaultIfNullOrWhiteSpace(this string? value, string defaultValue)

Parameters

value string

The string to evaluate.

defaultValue string

The fallback returned when value is null, empty, or contains only white-space characters. Must not be null.

Returns

string

value when it contains at least one non-white-space character; otherwise defaultValue.

Exceptions

ArgumentNullException

Thrown when defaultValue is null.

EndsWithOrdinal(string, string)

Returns a value indicating whether value ends with valueToFind under Ordinal.

public static bool EndsWithOrdinal(this string value, string valueToFind)

Parameters

value string

The string to inspect. Must not be null.

valueToFind string

The suffix to locate. Must not be null.

Returns

bool

true when value ends with valueToFind under ordinal comparison; otherwise false.

Exceptions

ArgumentNullException

Thrown when value or valueToFind is null.

EndsWithOrdinalIgnoreCase(string, string)

Returns a value indicating whether value ends with valueToFind under OrdinalIgnoreCase.

public static bool EndsWithOrdinalIgnoreCase(this string value, string valueToFind)

Parameters

value string

The string to inspect. Must not be null.

valueToFind string

The suffix to locate. Must not be null.

Returns

bool

true when value ends with valueToFind under case-insensitive ordinal comparison; otherwise false.

Exceptions

ArgumentNullException

Thrown when value or valueToFind is null.

EnsureEndsWith(string, string, StringComparison)

Returns value guaranteed to end with suffix, appending the suffix only when it is not already present.

public static string EnsureEndsWith(this string value, string suffix, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to qualify. Must not be null.

suffix string

The suffix that the result must end with. Must not be null.

comparison StringComparison

The comparison rule used to test whether value already ends with suffix. Defaults to Ordinal.

Returns

string

value when it already ends with suffix under comparison; otherwise a new string equal to value concatenated with suffix.

Examples

"report".EnsureEndsWith(".txt");      // "report.txt"
"report.txt".EnsureEndsWith(".txt");  // "report.txt" (suffix already present)

Exceptions

ArgumentNullException

Thrown when value or suffix is null.

EnsureStartsWith(string, string, StringComparison)

Returns value guaranteed to begin with prefix, prepending the prefix only when it is not already present.

public static string EnsureStartsWith(this string value, string prefix, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to qualify. Must not be null.

prefix string

The prefix that the result must begin with. Must not be null.

comparison StringComparison

The comparison rule used to test whether value already begins with prefix. Defaults to Ordinal.

Returns

string

value when it already starts with prefix under comparison; otherwise a new string equal to prefix concatenated with value.

Examples

"api/users".EnsureStartsWith("/");   // "/api/users"
"/api/users".EnsureStartsWith("/");  // "/api/users" (prefix already present)

Exceptions

ArgumentNullException

Thrown when value or prefix is null.

EnsureTrailingNewLine(string, string)

Returns value guaranteed to end with newline, appending the terminator only when it is not already present.

public static string EnsureTrailingNewLine(this string value, string newline = "\n")

Parameters

value string

The string to terminate. Must not be null.

newline string

The terminator to ensure. Defaults to "\n" (LF). Must not be null or empty.

Returns

string

value when it already ends with newline; otherwise a new string equal to value with newline appended.

Examples

"line".EnsureTrailingNewLine();    // "line\n"
"line\n".EnsureTrailingNewLine();  // "line\n" (already terminated)

Remarks

Comparison is ordinal - only the exact byte sequence specified by newline counts as already terminated. A value ending in "\r\n" is not considered to end in "\n" for the purposes of this method.

Exceptions

ArgumentNullException

Thrown when value or newline is null.

ArgumentException

Thrown when newline is the empty string.

EqualsOrdinalIgnoreCase(string?, string?)

Returns a value indicating whether value equals other under OrdinalIgnoreCase.

public static bool EqualsOrdinalIgnoreCase(this string? value, string? other)

Parameters

value string

The receiver string; may be null.

other string

The other string; may be null.

Returns

bool

true when both strings are null, or when neither is null and the characters compare equal under case-insensitive ordinal comparison; otherwise false.

Remarks

Convenience shortcut for string.Equals(value, other, StringComparison.OrdinalIgnoreCase).

FromBase64ToString(string, Encoding?)

Decodes the Base64-encoded value back into a string using encoding (or UTF8 when encoding is null) to interpret the decoded bytes.

public static string FromBase64ToString(this string value, Encoding? encoding = null)

Parameters

value string

The Base64-encoded input. Must not be null.

encoding Encoding

The text encoding used to interpret the decoded bytes. Defaults to UTF8 when null.

Returns

string

The decoded string.

Remarks

Named FromBase64ToString rather than FromBase64String to avoid colliding with the existing byte-returning helpers in Bodu.Text.Encoding.BinaryEncodingExtensions.

Exceptions

ArgumentNullException

Thrown when value is null.

FormatException

Thrown when value does not contain valid Base64.

HasText(string?)

Returns a value indicating whether value is non-null, non-empty, and contains at least one character that is not white space.

public static bool HasText(this string? value)

Parameters

value string

The string to inspect.

Returns

bool

true when value contains at least one non-white-space character; false when value is null, empty, or consists solely of white-space characters.

Remarks

Provides the positive form of IsNullOrWhiteSpace(string) so call sites can express "has meaningful text" affirmatively in LINQ predicates and conditional expressions.

Indent(string, int, char)

Returns value with count copies of indentChar prepended to every line.

public static string Indent(this string value, int count, char indentChar = ' ')

Parameters

value string

The source text. Must not be null.

count int

The number of indent characters to prepend per line. Must be non-negative.

indentChar char

The character used to indent. Defaults to a regular space.

Returns

string

The indented text.

Remarks

Line boundaries are recognised at \r\n, \n, and bare \r. Empty trailing lines (a trailing newline followed by nothing) are not indented. When count is zero the input is returned unchanged.

Exceptions

ArgumentNullException

Thrown when value is null.

ArgumentOutOfRangeException

Thrown when count is negative.

IsOneOf(string, IEqualityComparer<string>, params string[])

Returns a value indicating whether value equals any element of values under the rule supplied by comparer.

public static bool IsOneOf(this string value, IEqualityComparer<string> comparer, params string[] values)

Parameters

value string

The candidate string. Must not be null.

comparer IEqualityComparer<string>

The equality comparer used to match value against each element. Must not be null.

values string[]

The candidate set. Must not be null.

Returns

bool

true when any element of values equals value under comparer; otherwise false.

Exceptions

ArgumentNullException

Thrown when value, comparer, or values is null.

IsOneOf(string, params string[])

Returns a value indicating whether value equals any element of values under ordinal comparison.

public static bool IsOneOf(this string value, params string[] values)

Parameters

value string

The candidate string. Must not be null.

values string[]

The candidate set. Must not be null. Individual elements may be null and never match value.

Returns

bool

true when any element of values equals value under Ordinal; otherwise false.

Exceptions

ArgumentNullException

Thrown when value or values is null.

IsValidIdentifier(string)

Returns a value indicating whether value is a syntactically valid C# identifier (a letter or underscore followed by zero or more letters, digits, underscores, or connector punctuation).

public static bool IsValidIdentifier(this string value)

Parameters

value string

The string to test.

Returns

bool

true when value is non-empty and every character is a permitted identifier character; otherwise false.

Remarks

The rules follow the C# 5 ECMA-334 identifier grammar at a character level - the first character must be a letter (any UnicodeCategory in the letter family) or an underscore, and subsequent characters must additionally permit decimal digits, connector punctuation, and combining or formatting marks. Reserved keywords (if, class, etc.) are not rejected because the keyword set changes with the C# language version; callers needing keyword validation should compose this method with a custom keyword check.

The empty string returns false because an identifier must contain at least one character.

Exceptions

ArgumentNullException

Thrown when value is null.

KeepDigits(string)

Returns value filtered down to its Unicode digit characters.

public static string KeepDigits(this string value)

Parameters

value string

The string to filter. Must not be null.

Returns

string

A new string containing only the digit characters from value.

Remarks

Membership is determined via IsDigit(char), which recognises every Unicode digit (Nd) character - not just ASCII 0-9.

Exceptions

ArgumentNullException

Thrown when value is null.

KeepLetters(string)

Returns value filtered down to its Unicode letter characters.

public static string KeepLetters(this string value)

Parameters

value string

The string to filter. Must not be null.

Returns

string

A new string containing only the letter characters from value.

Remarks

Membership is determined via IsLetter(char), which recognises every Unicode letter category (Lu, Ll, Lt, Lm, Lo). ASCII digits, punctuation, whitespace, and control characters are stripped.

Exceptions

ArgumentNullException

Thrown when value is null.

KeepLettersAndDigits(string)

Returns value filtered down to its Unicode letter and digit characters.

public static string KeepLettersAndDigits(this string value)

Parameters

value string

The string to filter. Must not be null.

Returns

string

A new string containing only the letter and digit characters from value.

Exceptions

ArgumentNullException

Thrown when value is null.

KeepWhere(string, Func<char, bool>)

Returns value filtered down to the characters for which predicate returns true.

public static string KeepWhere(this string value, Func<char, bool> predicate)

Parameters

value string

The string to filter. Must not be null.

predicate Func<char, bool>

The selector evaluated for each character. Must not be null.

Returns

string

A new string containing only the characters where predicate returned true . When every character is kept, the original instance is returned.

Exceptions

ArgumentNullException

Thrown when value or predicate is null.

NormalizeLineEndings(string, string)

Returns value with every CRLF (\r\n), CR (\r), and LF (\n) sequence replaced by newline.

public static string NormalizeLineEndings(this string value, string newline = "\n")

Parameters

value string

The string to normalize. Must not be null.

newline string

The replacement line terminator. Defaults to "\n" (LF). May be empty to strip all line endings. Must not be null.

Returns

string

A new string in which every recognised line ending in value has been replaced by newline. When value contains no line endings, the original instance is returned unchanged.

Remarks

CRLF pairs are treated as a single line ending and replaced by exactly one newline. Other Unicode line separators (U+2028, U+2029, NEL U+0085) are not touched.

Exceptions

ArgumentNullException

Thrown when value or newline is null.

NullIfEmpty(string?)

Returns null when value is null or the empty string; otherwise returns value unchanged.

public static string? NullIfEmpty(this string? value)

Parameters

value string

The string to evaluate.

Returns

string

null when value is null or Empty ; otherwise the original value.

Remarks

Useful for collapsing the "missing" and "blank" cases into a single null sentinel - for example, request.Title.NullIfEmpty() ?? defaultTitle.

NullIfWhiteSpace(string?)

Returns null when value is null, empty, or consists solely of white-space characters; otherwise returns value unchanged.

public static string? NullIfWhiteSpace(this string? value)

Parameters

value string

The string to evaluate.

Returns

string

null when value is null, empty, or white-space-only; otherwise the original value.

Remarks

Useful for input sanitisation pipelines where whitespace-only entries should be treated as missing data.

Outdent(string, int, char)

Returns value with up to count leading occurrences of indentChar stripped from each line.

public static string Outdent(this string value, int count, char indentChar = ' ')

Parameters

value string

The source text. Must not be null.

count int

The maximum number of leading indent characters to remove per line. Must be non-negative.

indentChar char

The indent character to strip. Defaults to a regular space.

Returns

string

The outdented text.

Remarks

The inverse of Indent(string, int, char). Lines that contain fewer than count leading indentChar characters are stripped of however many are present - no exception is raised. Line boundaries follow the same rules as Indent(string, int, char) (\r\n, \n, bare \r).

Exceptions

ArgumentNullException

Thrown when value is null.

ArgumentOutOfRangeException

Thrown when count is negative.

Parenthesize(string)

Returns value wrapped in round-bracket characters ((…)).

public static string Parenthesize(this string value)

Parameters

value string

The string to wrap. Must not be null.

Returns

string

The parenthesised string.

Exceptions

ArgumentNullException

Thrown when value is null.

ParseSpan<T>(string)

Parses value into the requested T using the ISpanParsable<TSelf> contract and InvariantCulture, routing through the underlying character span to avoid intermediate string allocation.

public static T ParseSpan<T>(this string value) where T : ISpanParsable<T>

Parameters

value string

The string to parse. Must not be null.

Returns

T

The parsed value.

Type Parameters

T

The target type, which must implement ISpanParsable<TSelf>.

Exceptions

ArgumentNullException

Thrown when value is null.

FormatException

Thrown when value is not in a valid format for T.

OverflowException

Thrown when value represents a value outside the range supported by T.

Parse<T>(string)

Parses value into the requested T using the IParsable<TSelf> contract and InvariantCulture as the format provider.

public static T Parse<T>(this string value) where T : IParsable<T>

Parameters

value string

The string to parse. Must not be null.

Returns

T

The parsed value.

Type Parameters

T

The target type, which must implement IParsable<TSelf>.

Remarks

Provides a fluent "42".Parse<int>() form that flows from the string variable, in addition to the static T.Parse factory. The invariant culture is used by default to keep behaviour stable across machines and locales.

Exceptions

ArgumentNullException

Thrown when value is null.

FormatException

Thrown when value is not in a valid format for T.

OverflowException

Thrown when value represents a value outside the range supported by T.

PrefixLines(string, string)

Returns value with prefix prepended to every line.

public static string PrefixLines(this string value, string prefix)

Parameters

value string

The source text. Must not be null.

prefix string

The string to prepend to each line. Must not be null.

Returns

string

The prefixed text.

Remarks

Line boundaries are recognised at \r\n, \n, and bare \r. An empty prefix returns the input unchanged. Commonly used to add a comment marker to a block of source - e.g. "line1\nline2".PrefixLines("// ").

Exceptions

ArgumentNullException

Thrown when either argument is null.

Quote(string)

Returns value wrapped in straight double-quote characters ("…").

public static string Quote(this string value)

Parameters

value string

The string to wrap. Must not be null.

Returns

string

The double-quoted string.

Remarks

This method does not escape embedded quote characters. For CSV-style escaping use the helpers in the Bodu.Text.Delimited namespace.

Exceptions

ArgumentNullException

Thrown when value is null.

Remove(string, string, StringComparison)

Returns value with every occurrence of valueToRemove removed.

public static string Remove(this string value, string valueToRemove, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

valueToRemove string

The substring to remove. Must not be null or empty.

comparison StringComparison

The comparison rule used to locate occurrences of valueToRemove. Defaults to Ordinal.

Returns

string

A new string with the matches removed. When valueToRemove does not appear, the original instance is returned unchanged.

Remarks

This is the substring counterpart to the BCL Remove(int) family, which is index-based. Use TrimStart(params char[])/TrimEnd(params char[]) when the goal is to strip individual characters.

Exceptions

ArgumentNullException

Thrown when value or valueToRemove is null.

ArgumentException

Thrown when valueToRemove is the empty string.

RemoveControlCharacters(string)

Returns value with every Unicode control character removed.

public static string RemoveControlCharacters(this string value)

Parameters

value string

The string to inspect. Must not be null.

Returns

string

A new string with control characters stripped.

Remarks

Membership is determined via IsControl(char) which covers ASCII C0 control codes (U+0000-U+001F), DEL (U+007F), and the C1 control range (U+0080-U+009F). Tab, CR and LF count as control characters and are also removed.

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveDiacritics(string)

Returns value with combining diacritic marks removed, normalising accented Latin characters to their unaccented base form.

public static string RemoveDiacritics(this string value)

Parameters

value string

The string to strip. Must not be null.

Returns

string

The string with non-spacing combining marks stripped after Unicode FormD normalisation.

Remarks

The input is decomposed via FormD, which separates precomposed characters such as 'é' into a base character followed by a combining mark. Each resulting character whose Unicode category is NonSpacingMark is then dropped, leaving the base characters in place. The result is recomposed via FormC for consistent output.

This is the canonical pattern for accent-insensitive search keys and is intentionally limited to diacritic stripping - it does not transliterate non-Latin scripts (e.g. Cyrillic, CJK) and does not case-fold. For full search normalisation combine this with ToLowerInvariant and CollapseWhitespace(string).

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveDigits(string)

Returns value with every Unicode digit character removed.

public static string RemoveDigits(this string value)

Parameters

value string

The string to inspect. Must not be null.

Returns

string

A new string with digit characters stripped.

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveLineEndings(string)

Returns value with every carriage-return (\r) and line-feed (\n) character removed.

public static string RemoveLineEndings(this string value)

Parameters

value string

The string to strip. Must not be null.

Returns

string

A new string containing none of the \r or \n characters from value. When value already contains no line-ending characters, the original instance is returned unchanged.

Remarks

Only ASCII CR and LF are removed. Other Unicode line separators (U+2028, U+2029, NEL U+0085, vertical tab U+000B, form feed U+000C) are preserved. Use NormalizeLineEndings(string, string) with an empty string when stripping all newline-equivalent characters is required.

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveMany(string, params string[])

Returns value with every occurrence of each entry in valuesToRemove removed under ordinal comparison, applied sequentially in array order.

public static string RemoveMany(this string value, params string[] valuesToRemove)

Parameters

value string

The string to inspect. Must not be null.

valuesToRemove string[]

The substrings to remove. Must not be null; individual entries must not be null or empty.

Returns

string

A new string with all matches removed. When valuesToRemove is empty, the original instance is returned unchanged.

Exceptions

ArgumentNullException

Thrown when value or valuesToRemove is null, or when any element of valuesToRemove is null.

ArgumentException

Thrown when any element of valuesToRemove is the empty string.

RemovePrefix(string, string, StringComparison)

Returns value with a single leading occurrence of prefix removed when present.

public static string RemovePrefix(this string value, string prefix, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

prefix string

The prefix to remove. Must not be null.

comparison StringComparison

The comparison rule used to detect prefix at the start of value. Defaults to Ordinal.

Returns

string

value without the leading prefix when present; otherwise the original instance.

Remarks

Removes at most one occurrence of prefix. Use the BCL TrimStart(params char[]) when greedy removal of character-level prefixes is required.

Exceptions

ArgumentNullException

Thrown when value or prefix is null.

RemovePunctuation(string)

Returns value with every Unicode punctuation character removed.

public static string RemovePunctuation(this string value)

Parameters

value string

The string to inspect. Must not be null.

Returns

string

A new string with punctuation characters stripped.

Remarks

Membership is determined via IsPunctuation(char) which covers the Unicode punctuation categories (Pc, Pd, Pe, Pf, Pi, Po, Ps).

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveSuffix(string, string, StringComparison)

Returns value with a single trailing occurrence of suffix removed when present.

public static string RemoveSuffix(this string value, string suffix, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to inspect. Must not be null.

suffix string

The suffix to remove. Must not be null.

comparison StringComparison

The comparison rule used to detect suffix at the end of value. Defaults to Ordinal.

Returns

string

value without the trailing suffix when present; otherwise the original instance.

Remarks

Removes at most one occurrence of suffix. Use the BCL TrimEnd(params char[]) when greedy removal of character-level suffixes is required.

Exceptions

ArgumentNullException

Thrown when value or suffix is null.

RemoveTrailingNewLine(string)

Returns value with a single trailing line ending removed when present.

public static string RemoveTrailingNewLine(this string value)

Parameters

value string

The string to trim. Must not be null.

Returns

string

value with the last "\r\n", "\n", or "\r" sequence removed. Returns the original instance unchanged when value does not end with a line terminator.

Remarks

Only one trailing line terminator is removed. Repeated trailing newlines are intentionally preserved - use TrimEnd(params char[]) with '\r','\n' when greedy stripping is required.

Exceptions

ArgumentNullException

Thrown when value is null.

RemoveWhere(string, Func<char, bool>)

Returns value with every character for which predicate returns true removed.

public static string RemoveWhere(this string value, Func<char, bool> predicate)

Parameters

value string

The string to filter. Must not be null.

predicate Func<char, bool>

The selector evaluated for each character. Must not be null.

Returns

string

A new string with the matching characters removed. When no character matches, the original instance is returned.

Exceptions

ArgumentNullException

Thrown when value or predicate is null.

RemoveWhitespace(string)

Returns value with every white-space character removed.

public static string RemoveWhitespace(this string value)

Parameters

value string

The string to strip. Must not be null.

Returns

string

A new string containing only the non-white-space characters from value. When value already contains no white-space, the original instance is returned unchanged.

Remarks

White-space is detected via IsWhiteSpace(char) so Unicode separators (NBSP, line terminators, tab) are all removed.

Exceptions

ArgumentNullException

Thrown when value is null.

ReplaceMany(string, IReadOnlyDictionary<string, string>)

Returns value with every key from replacements replaced by its associated value, applied sequentially in dictionary enumeration order under ordinal comparison.

public static string ReplaceMany(this string value, IReadOnlyDictionary<string, string> replacements)

Parameters

value string

The string to transform. Must not be null.

replacements IReadOnlyDictionary<string, string>

The map of search-and-replace pairs. Must not be null; keys must not be null or empty; values may be null or empty.

Returns

string

A new string with all replacements applied. When replacements is empty, the original instance is returned.

Remarks

Replacements are applied sequentially - output of an earlier replacement is visible to a later one. Pre-order keys to avoid cascading substitutions when independence is required.

Exceptions

ArgumentNullException

Thrown when value or replacements is null, or when any key in replacements is null.

ArgumentException

Thrown when any key in replacements is the empty string.

ReplaceOrdinalIgnoreCase(string, string, string?)

Returns value with every occurrence of oldValue replaced by newValue using case-insensitive ordinal comparison.

public static string ReplaceOrdinalIgnoreCase(this string value, string oldValue, string? newValue)

Parameters

value string

The string to search. Must not be null.

oldValue string

The substring to replace. Must not be null or empty.

newValue string

The replacement substring. May be null or empty.

Returns

string

A new string with each case-insensitive occurrence of oldValue replaced.

Exceptions

ArgumentNullException

Thrown when value or oldValue is null.

ArgumentException

Thrown when oldValue is the empty string.

SingleQuote(string)

Returns value wrapped in straight single-quote characters ('…').

public static string SingleQuote(this string value)

Parameters

value string

The string to wrap. Must not be null.

Returns

string

The single-quoted string.

Remarks

This method does not escape embedded apostrophes.

Exceptions

ArgumentNullException

Thrown when value is null.

SliceSafe(string, int)

Returns the substring of value starting at startIndex, clamping out-of-range indices instead of throwing.

public static string SliceSafe(this string value, int startIndex)

Parameters

value string

The source string. Must not be null.

startIndex int

The zero-based starting index. May be negative or beyond the end of the string.

Returns

string

The substring beginning at the clamped startIndex. Returns the original instance when startIndex is zero or negative; returns Empty when startIndex is greater than or equal to value.Length.

Exceptions

ArgumentNullException

Thrown when value is null.

SliceSafe(string, int, int)

Returns a substring of value starting at startIndex with the requested length, clamping out-of-range arguments instead of throwing.

public static string SliceSafe(this string value, int startIndex, int length)

Parameters

value string

The source string. Must not be null.

startIndex int

The zero-based starting index. Negative values clamp to zero.

length int

The maximum number of characters to take. Negative values produce an empty string. The actual length returned is clamped to the remaining characters in value.

Returns

string

The substring starting at the clamped startIndex of at most length characters.

Exceptions

ArgumentNullException

Thrown when value is null.

SplitLines(string, bool)

Returns a sequence of lines from value, splitting on every CRLF, CR, or LF boundary.

public static IEnumerable<string> SplitLines(this string value, bool removeEmptyLines = false)

Parameters

value string

The string to split. Must not be null.

removeEmptyLines bool

When true, empty lines are skipped. Defaults to false so callers receive a 1:1 mapping with the original line boundaries.

Returns

IEnumerable<string>

An enumerable yielding each line of value with the terminator removed. An empty input returns an empty sequence.

Remarks

CRLF is treated as a single line ending. Unlike Split(params char[]), a trailing line terminator does not produce a final empty line - the contract matches typical "lines in a file" reading semantics.

Exceptions

ArgumentNullException

Thrown when value is null.

StartsWithOrdinal(string, string)

Returns a value indicating whether value begins with valueToFind under Ordinal.

public static bool StartsWithOrdinal(this string value, string valueToFind)

Parameters

value string

The string to inspect. Must not be null.

valueToFind string

The prefix to locate. Must not be null.

Returns

bool

true when value starts with valueToFind under ordinal comparison; otherwise false.

Remarks

Provides an explicit-Ordinal alternative to the BCL StartsWith(string) overload, which defaults to CurrentCulture and can produce surprising results across locales.

Exceptions

ArgumentNullException

Thrown when value or valueToFind is null.

StartsWithOrdinalIgnoreCase(string, string)

Returns a value indicating whether value begins with valueToFind under OrdinalIgnoreCase.

public static bool StartsWithOrdinalIgnoreCase(this string value, string valueToFind)

Parameters

value string

The string to inspect. Must not be null.

valueToFind string

The prefix to locate. Must not be null.

Returns

bool

true when value starts with valueToFind under case-insensitive ordinal comparison; otherwise false.

Exceptions

ArgumentNullException

Thrown when value or valueToFind is null.

ToBase64(string, Encoding?)

Returns the Base64-encoded representation of value after encoding it with encoding (or UTF8 when encoding is null).

public static string ToBase64(this string value, Encoding? encoding = null)

Parameters

value string

The string to encode. Must not be null.

encoding Encoding

The text encoding used to convert value to bytes before Base64 encoding. Defaults to UTF8 when null.

Returns

string

The Base64-encoded string.

Remarks

Convenience wrapper over ToBase64String(byte[]) that avoids the boilerplate of converting the string to bytes manually. Pair with FromBase64ToString(string, Encoding?) for the inverse operation.

Exceptions

ArgumentNullException

Thrown when value is null.

ToCamelCase(string)

Converts value to camelCase: the first word is lower-cased and each subsequent word has its first character upper-cased, with separators removed.

public static string ToCamelCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The camelCase form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Casing changes use the configured culture.

Exceptions

ArgumentNullException

Thrown when value is null.

ToCamelCase(string, WordCasingOptions)

Converts value to camelCase under the supplied options.

public static string ToCamelCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The camelCase form of value.

Remarks

The first word is fully lower-cased. Each subsequent word is capitalised unless it is a recognised mixed-case word, which is emitted verbatim.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToConstantCase(string)

Converts value to CONSTANT_CASE: upper-cased words joined by underscores.

public static string ToConstantCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The CONSTANT_CASE form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Every word is upper-cased.

Exceptions

ArgumentNullException

Thrown when value is null.

ToConstantCase(string, WordCasingOptions)

Converts value to CONSTANT_CASE under the supplied options.

public static string ToConstantCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The CONSTANT_CASE form of value.

Remarks

Every word, including acronyms, is upper-cased before joining.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToDotCase(string)

Converts value to dot.case: lower-cased words joined by periods.

public static string ToDotCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The dot.case form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Every word, including acronyms, is lower-cased.

Exceptions

ArgumentNullException

Thrown when value is null.

ToDotCase(string, WordCasingOptions)

Converts value to dot.case under the supplied options.

public static string ToDotCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The dot.case form of value.

Remarks

Every word, including acronyms, is lower-cased before joining.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToIdentifier(string)

Converts value into a syntactically valid C# identifier by removing characters that are not permitted in identifiers and preserving the original casing of the remaining characters.

public static string ToIdentifier(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

A new identifier-safe string. If the cleaned form does not begin with a permitted identifier-start character, an underscore is prepended.

Remarks

Equivalent to value.ToIdentifier(IdentifierCase.Preserve). When the input contains no valid identifier characters at all, a single underscore is returned so the result is still a valid identifier.

Exceptions

ArgumentNullException

Thrown when value is null.

ToIdentifier(string, IdentifierCase)

Converts value into a syntactically valid C# identifier and reshapes the detected words to identifierCase.

public static string ToIdentifier(this string value, IdentifierCase identifierCase)

Parameters

value string

The string to convert.

identifierCase IdentifierCase

The target casing applied to the detected words.

Returns

string

A new identifier-safe string in the chosen casing. If the result would otherwise start with a digit, an underscore is prepended so the returned value still satisfies the identifier grammar.

Remarks

Words are detected with the same tokeniser and boundary rules the casing converters use ( Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions)), configured via Bodu.Extensions.StringExtensions.s_identifierWordOptions to disable acronym canonicalisation and mixed-case-brand preservation so that only structural case, digit, and separator boundaries drive word detection. Non-letter / non-digit / non-underscore characters are treated as separators and discarded.

Exceptions

ArgumentNullException

Thrown when value is null.

ArgumentOutOfRangeException

Thrown when identifierCase is not a defined IdentifierCase value.

ToKebabCase(string)

Converts value to kebab-case: lower-cased words joined by hyphens.

public static string ToKebabCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The kebab-case form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Every word, including acronyms, is lower-cased.

Exceptions

ArgumentNullException

Thrown when value is null.

ToKebabCase(string, WordCasingOptions)

Converts value to kebab-case under the supplied options.

public static string ToKebabCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The kebab-case form of value.

Remarks

Every word, including acronyms, is lower-cased before joining.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToPascalCase(string)

Converts value to PascalCase: every word has its first character upper-cased and the remaining characters lower-cased, with separators removed.

public static string ToPascalCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The PascalCase form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Casing changes use the configured culture.

Exceptions

ArgumentNullException

Thrown when value is null.

ToPascalCase(string, WordCasingOptions)

Converts value to PascalCase under the supplied options.

public static string ToPascalCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The PascalCase form of value.

Remarks

Every word is capitalised unless it is a recognised mixed-case word, which is emitted verbatim.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToSafeFileName(string)

Returns value with every character that GetInvalidFileNameChars() reports as invalid for a file name replaced by an underscore.

public static string ToSafeFileName(this string value)

Parameters

value string

The candidate file name to sanitise.

Returns

string

A string in which each invalid character has been replaced by '' - the original instance when nothing required replacement. Returns "" when the input is empty so that the result is never itself an empty file name.

Remarks

The invalid character set is platform-dependent - Windows reports more invalid characters than POSIX systems do. Callers writing files for a known target platform should construct the invalid set explicitly rather than relying on the current platform's defaults.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSafePathSegment(string)

Returns value with every character that GetInvalidFileNameChars() reports as invalid for a single path segment (plus the platform path separators) replaced by an underscore.

public static string ToSafePathSegment(this string value)

Parameters

value string

The candidate path segment to sanitise.

Returns

string

A string in which each invalid character - including DirectorySeparatorChar and AltDirectorySeparatorChar - has been replaced by ''; the original instance when nothing required replacement. Returns "" when the input is empty so that the result is never itself an empty segment.

Remarks

Use this when composing a path from user input where each component must be a single segment without embedded separators. For a full file name (no embedded separators required as a rule), prefer ToSafeFileName(string) - the two differ only in whether path separators are stripped.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSentenceCase(string)

Returns value with the first letter of every sentence capitalised and every other letter lower-cased, using InvariantCulture.

public static string ToSentenceCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The sentence-case form of value.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSentenceCase(string, SentenceCaseOptions)

Returns value in sentence case under the supplied options.

public static string ToSentenceCase(this string value, SentenceCaseOptions options)

Parameters

value string

The string to convert. Must not be null.

options SentenceCaseOptions

Flags that adjust acronym preservation.

Returns

string

The sentence-case form of value.

Remarks

A new sentence starts at the beginning of the input and after every ., !, or ?. The flag-based overload maps onto WordCasingOptions with an empty acronym catalogue, so only fully-uppercase input tokens are preserved as acronyms.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSentenceCase(string, WordCasingOptions)

Returns value in sentence case under the supplied options, applying acronym-aware tokenisation, mixed-case-word preservation, and culture-sensitive casing.

public static string ToSentenceCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The sentence-case form of value.

Remarks

When the input contains white-space its original spacing and punctuation are preserved: every letter is lower-cased except the first letter of each sentence, which is capitalised. A new sentence starts at the beginning and after every ., !, or ?. When the input contains no white-space it is treated as a compound identifier, tokenised, and re-joined with single spaces.

Known acronyms and fully-uppercase tokens keep their acronym spelling when PreserveAcronyms is set; recognised mixed-case words are emitted verbatim when PreserveMixedCaseWords is set. Only sentence terminators - never an apostrophe - trigger capitalisation, so o'connor becomes O'connor.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToSlug(string)

Converts value to a URL-friendly slug: lower-cased words joined by hyphens with diacritics normalised and punctuation removed.

public static string ToSlug(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The slug form of value.

Remarks

Equivalent to calling ToSlug(string, SlugOptions) with Default.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSlug(string, SlugOptions)

Converts value to a URL-friendly slug under the supplied options.

public static string ToSlug(this string value, SlugOptions options)

Parameters

value string

The string to convert. Must not be null.

options SlugOptions

The separator, casing, diacritic, and length configuration. Must not be null.

Returns

string

The slug form of value.

Remarks

When NormalizeDiacritics is set the input is first transliterated: the German sharp-s (ß) becomes ss and combining diacritic marks are stripped via RemoveDiacritics(string). The result is then tokenised, optionally lower-cased, and joined with Separator.

When MaxLength is greater than zero the slug is truncated at a separator boundary so the result never exceeds the limit and never ends with a dangling separator.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToSnakeCase(string)

Converts value to snake_case: lower-cased words joined by underscores.

public static string ToSnakeCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The snake_case form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Every word, including acronyms, is lower-cased.

Exceptions

ArgumentNullException

Thrown when value is null.

ToSnakeCase(string, WordCasingOptions)

Converts value to snake_case under the supplied options.

public static string ToSnakeCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The snake_case form of value.

Remarks

Every word, including acronyms, is lower-cased before joining.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToTitleCase(string)

Returns value with the first character of every word capitalised and the rest lower-cased, using InvariantCulture.

public static string ToTitleCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The title-case form of value.

Exceptions

ArgumentNullException

Thrown when value is null.

ToTitleCase(string, TitleCaseOptions)

Returns value in title case under the supplied options.

public static string ToTitleCase(this string value, TitleCaseOptions options)

Parameters

value string

The string to convert. Must not be null.

options TitleCaseOptions

Flags that adjust acronym preservation and small-word handling.

Returns

string

The title-case form of value.

Remarks

The flag-based overload maps onto WordCasingOptions with an empty acronym catalogue, so only fully-uppercase input tokens are preserved as acronyms - lower-case words are never promoted to a canonical acronym spelling.

Exceptions

ArgumentNullException

Thrown when value is null.

ToTitleCase(string, WordCasingOptions)

Returns value in title case under the supplied options, applying acronym-aware tokenisation, mixed-case-word preservation, and culture-sensitive casing.

public static string ToTitleCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, minor-word, and culture configuration. Must not be null.

Returns

string

The title-case form of value.

Remarks

When the input contains white-space it is treated as a phrase: words are split on white-space, a joining hyphen is kept attached, and trailing sentence punctuation is preserved. When the input contains no white-space it is treated as a compound identifier and every separator becomes a single space.

Known acronyms and fully-uppercase tokens keep their acronym spelling when PreserveAcronyms is set; recognised mixed-case words are emitted verbatim when PreserveMixedCaseWords is set. When LowerCaseMinorWords is set, minor words that are neither the first nor the last word are down-cased. The first letter after an apostrophe is capitalised so that personal names such as o'connor become O'Connor.

Exceptions

ArgumentNullException

Thrown when value or options is null.

ToTrainCase(string)

Converts value to Train-Case: each word has its first character upper-cased and the rest lower-cased, joined by hyphens.

public static string ToTrainCase(this string value)

Parameters

value string

The string to convert. Must not be null.

Returns

string

The Train-Case form of value.

Remarks

Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Casing changes use the configured culture.

Exceptions

ArgumentNullException

Thrown when value is null.

ToTrainCase(string, WordCasingOptions)

Converts value to Train-Case under the supplied options.

public static string ToTrainCase(this string value, WordCasingOptions options)

Parameters

value string

The string to convert. Must not be null.

options WordCasingOptions

The acronym, mixed-case, and culture configuration. Must not be null.

Returns

string

The Train-Case form of value.

Remarks

Every word is capitalised unless it is a recognised mixed-case word, which is emitted verbatim.

Exceptions

ArgumentNullException

Thrown when value or options is null.

TrimOrEmpty(string?)

Returns the trimmed form of value, or Empty when value is null.

public static string TrimOrEmpty(this string? value)

Parameters

value string

The string to trim.

Returns

string

Empty when value is null; otherwise the result of Trim() applied to value.

Remarks

Avoids the common mistake of writing value?.Trim() ?? string.Empty manually - the null propagation precedes the trim call so callers can safely chain further string operations on the result.

TrimToNull(string?)

Returns the trimmed form of value, or null when value is null or the trimmed result is empty.

public static string? TrimToNull(this string? value)

Parameters

value string

The string to trim.

Returns

string

null when value is null or trims to an empty string; otherwise the trimmed value.

Remarks

Useful for input sanitisation pipelines where whitespace-only entries should collapse to a missing-data sentinel rather than an empty string.

Truncate(string, int)

Returns value truncated to at most maxLength characters.

public static string Truncate(this string value, int maxLength)

Parameters

value string

The string to truncate. Must not be null.

maxLength int

The maximum length to retain. Must be non-negative.

Returns

string

value when its length is at most maxLength; otherwise the first maxLength characters.

Exceptions

ArgumentNullException

Thrown when value is null.

ArgumentOutOfRangeException

Thrown when maxLength is negative.

Truncate(string, int, string)

Returns value truncated to at most maxLength characters, appending ellipsis to indicate truncation.

public static string Truncate(this string value, int maxLength, string ellipsis)

Parameters

value string

The string to truncate. Must not be null.

maxLength int

The maximum total length to retain, including ellipsis. Must be at least ellipsis.Length.

ellipsis string

The suffix appended when truncation occurs. Must not be null.

Returns

string

value when its length is at most maxLength; otherwise the first maxLength - ellipsis.Length characters followed by ellipsis.

Exceptions

ArgumentNullException

Thrown when value or ellipsis is null.

ArgumentOutOfRangeException

Thrown when maxLength is smaller than ellipsis.Length.

TruncateMiddle(string, int, string)

Returns value truncated to at most maxLength characters by keeping the beginning and end intact and inserting separator in the middle.

public static string TruncateMiddle(this string value, int maxLength, string separator = "…")

Parameters

value string

The string to truncate. Must not be null.

maxLength int

The maximum total length to retain, including separator. Must be at least separator.Length.

separator string

The marker inserted in place of the omitted middle. Defaults to the ellipsis character "…". Must not be null.

Returns

string

value when its length is at most maxLength; otherwise a new string composed of the leading portion, separator, and the trailing portion of value such that the total length equals maxLength. When the remaining budget cannot be evenly split, the extra character goes to the prefix.

Examples

"hello-world-foo-bar".TruncateMiddle(11);          // "hello…o-bar"
"abcdefghij".TruncateMiddle(7, "...");             // "ab...ij"

Exceptions

ArgumentNullException

Thrown when value or separator is null.

ArgumentOutOfRangeException

Thrown when maxLength is smaller than separator.Length.

TryParseSpan<T>(string, out T)

Attempts to parse value into the requested T using the ISpanParsable<TSelf> contract and InvariantCulture, routing through the underlying character span.

public static bool TryParseSpan<T>(this string value, out T result) where T : ISpanParsable<T>

Parameters

value string

The string to parse.

result T

When this method returns true, contains the parsed value; otherwise the type's default value.

Returns

bool

true when value was parsed successfully; otherwise false.

Type Parameters

T

The target type, which must implement ISpanParsable<TSelf>.

Exceptions

ArgumentNullException

Thrown when value is null.

TryParse<T>(string, out T)

Attempts to parse value into the requested T using the IParsable<TSelf> contract and InvariantCulture.

public static bool TryParse<T>(this string value, out T result) where T : IParsable<T>

Parameters

value string

The string to parse.

result T

When this method returns true, contains the parsed value; otherwise the type's default value.

Returns

bool

true when value was parsed successfully; otherwise false.

Type Parameters

T

The target type, which must implement IParsable<TSelf>.

Exceptions

ArgumentNullException

Thrown when value is null.

UnprefixLines(string, string)

Returns value with one occurrence of prefix removed from the start of every line that begins with it.

public static string UnprefixLines(this string value, string prefix)

Parameters

value string

The source text. Must not be null.

prefix string

The prefix to strip from each line. Must not be null.

Returns

string

The text with the prefix removed from each prefixed line.

Remarks

The inverse of PrefixLines(string, string). Lines that do not begin with prefix are emitted unchanged. Comparison is ordinal. Line boundaries follow the usual \r\n / \n / \r recognition.

Exceptions

ArgumentNullException

Thrown when either argument is null.

Unwrap(string, string, string, StringComparison)

Returns value with prefix and suffix removed if both are present at their respective ends.

public static string Unwrap(this string value, string prefix, string suffix, StringComparison comparison = StringComparison.Ordinal)

Parameters

value string

The string to unwrap. Must not be null.

prefix string

The expected prefix. Must not be null.

suffix string

The expected suffix. Must not be null.

comparison StringComparison

The string comparison used for prefix and suffix matching.

Returns

string

The unwrapped string when both ends match; otherwise value unchanged. Unwrapping requires both ends to match - partial matches are left intact so the operation is reversible against Wrap(string, string, string).

Exceptions

ArgumentNullException

Thrown when any string argument is null.

Wrap(string, string, string)

Returns value with prefix prepended and suffix appended.

public static string Wrap(this string value, string prefix, string suffix)

Parameters

value string

The string to wrap. Must not be null.

prefix string

The string to prepend. Must not be null.

suffix string

The string to append. Must not be null.

Returns

string

The wrapped string.

Exceptions

ArgumentNullException

Thrown when any argument is null.

Applies to

ProductVersions
.NET8, 10