StringExtensions Class
Definition
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
valuestringThe string to inspect. Must not be null.
markerstringThe marker to locate. Must not be null.
comparisonStringComparisonThe comparison rule used to locate
marker. Defaults to Ordinal.
Returns
Examples
"user@example.com".After("@"); // "example.com"
"no-delimiter".After("@"); // null
Exceptions
- ArgumentNullException
Thrown when
valueormarkeris 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
valuestringThe string to inspect. Must not be null.
markerstringThe marker to locate. Must not be null.
comparisonStringComparisonThe comparison rule used to locate
marker. Defaults to Ordinal.
Returns
Exceptions
- ArgumentNullException
Thrown when
valueormarkeris 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
valuestringThe string to inspect. Must not be null.
markerstringThe marker to locate. Must not be null.
comparisonStringComparisonThe comparison rule used to locate
marker. Defaults to Ordinal.
Returns
Exceptions
- ArgumentNullException
Thrown when
valueormarkeris 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
valuestringThe string to inspect. Must not be null.
markerstringThe marker to locate. Must not be null.
comparisonStringComparisonThe comparison rule used to locate
marker. Defaults to Ordinal.
Returns
Exceptions
- ArgumentNullException
Thrown when
valueormarkeris 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
valuestringThe string to inspect. Must not be null.
startstringThe opening marker. Must not be null.
endstringThe closing marker. Must not be null.
comparisonStringComparisonThe 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, orendis null.
Brace(string)
Returns value wrapped in curly-brace characters ({…}).
public static string Brace(this string value)
Parameters
Returns
- string
The braced string.
Exceptions
- ArgumentNullException
Thrown when
valueis null.
Bracket(string)
Returns value wrapped in square-bracket characters ([…]).
public static string Bracket(this string value)
Parameters
Returns
- string
The bracketed string.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
Returns
- string
A new string where consecutive white-space characters have been replaced by a single space. When
valuecontains no runs of two or more white-space characters and no non-space white-space characters, the originalvalueis 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
valueis null.
ContainsOrdinalIgnoreCase(string, string)
Returns a value indicating whether value contains valueToFind under
OrdinalIgnoreCase.
public static bool ContainsOrdinalIgnoreCase(this string value, string valueToFind)
Parameters
valuestringThe string to search. Must not be null.
valueToFindstringThe substring to locate. Must not be null.
Returns
- bool
true when
valueToFindoccurs at least once withinvalueunder case-insensitive ordinal comparison; otherwise false.
Exceptions
- ArgumentNullException
Thrown when
valueorvalueToFindis 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
valuestringThe string to evaluate.
defaultValuestringThe fallback returned when
valueis null or empty. Must not be null.
Returns
- string
valuewhen it contains at least one character; otherwisedefaultValue.
Exceptions
- ArgumentNullException
Thrown when
defaultValueis 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
valuestringThe string to evaluate.
defaultValuestringThe fallback returned when
valueis null, empty, or contains only white-space characters. Must not be null.
Returns
- string
valuewhen it contains at least one non-white-space character; otherwisedefaultValue.
Exceptions
- ArgumentNullException
Thrown when
defaultValueis 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
valuestringThe string to inspect. Must not be null.
valueToFindstringThe suffix to locate. Must not be null.
Returns
Exceptions
- ArgumentNullException
Thrown when
valueorvalueToFindis 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
valuestringThe string to inspect. Must not be null.
valueToFindstringThe suffix to locate. Must not be null.
Returns
- bool
true when
valueends withvalueToFindunder case-insensitive ordinal comparison; otherwise false.
Exceptions
- ArgumentNullException
Thrown when
valueorvalueToFindis 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
valuestringThe string to qualify. Must not be null.
suffixstringThe suffix that the result must end with. Must not be null.
comparisonStringComparisonThe comparison rule used to test whether
valuealready ends withsuffix. Defaults to Ordinal.
Returns
- string
valuewhen it already ends withsuffixundercomparison; otherwise a new string equal tovalueconcatenated withsuffix.
Examples
"report".EnsureEndsWith(".txt"); // "report.txt"
"report.txt".EnsureEndsWith(".txt"); // "report.txt" (suffix already present)
Exceptions
- ArgumentNullException
Thrown when
valueorsuffixis 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
valuestringThe string to qualify. Must not be null.
prefixstringThe prefix that the result must begin with. Must not be null.
comparisonStringComparisonThe comparison rule used to test whether
valuealready begins withprefix. Defaults to Ordinal.
Returns
- string
valuewhen it already starts withprefixundercomparison; otherwise a new string equal toprefixconcatenated withvalue.
Examples
"api/users".EnsureStartsWith("/"); // "/api/users"
"/api/users".EnsureStartsWith("/"); // "/api/users" (prefix already present)
Exceptions
- ArgumentNullException
Thrown when
valueorprefixis 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
valuestringThe string to terminate. Must not be null.
newlinestringThe terminator to ensure. Defaults to
"\n"(LF). Must not be null or empty.
Returns
- string
valuewhen it already ends withnewline; otherwise a new string equal tovaluewithnewlineappended.
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
valueornewlineis null.- ArgumentException
Thrown when
newlineis 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
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
valuestringThe Base64-encoded input. Must not be null.
encodingEncodingThe 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
valueis null.- FormatException
Thrown when
valuedoes 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
valuestringThe string to inspect.
Returns
- bool
true when
valuecontains at least one non-white-space character; false whenvalueis 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
valuestringThe source text. Must not be null.
countintThe number of indent characters to prepend per line. Must be non-negative.
indentCharcharThe 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
valueis null.- ArgumentOutOfRangeException
Thrown when
countis 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
valuestringThe candidate string. Must not be null.
comparerIEqualityComparer<string>The equality comparer used to match
valueagainst each element. Must not be null.valuesstring[]The candidate set. Must not be null.
Returns
Exceptions
- ArgumentNullException
Thrown when
value,comparer, orvaluesis 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
valuestringThe candidate string. Must not be null.
valuesstring[]The candidate set. Must not be null. Individual elements may be null and never match
value.
Returns
Exceptions
- ArgumentNullException
Thrown when
valueorvaluesis 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
valuestringThe string to test.
Returns
- bool
true when
valueis 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
valueis null.
KeepDigits(string)
Returns value filtered down to its Unicode digit characters.
public static string KeepDigits(this string value)
Parameters
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
valueis null.
KeepLetters(string)
Returns value filtered down to its Unicode letter characters.
public static string KeepLetters(this string value)
Parameters
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
valueis null.
KeepLettersAndDigits(string)
Returns value filtered down to its Unicode letter and digit characters.
public static string KeepLettersAndDigits(this string value)
Parameters
Returns
- string
A new string containing only the letter and digit characters from
value.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe string to filter. Must not be null.
predicateFunc<char, bool>The selector evaluated for each character. Must not be null.
Returns
- string
A new string containing only the characters where
predicatereturned true . When every character is kept, the original instance is returned.
Exceptions
- ArgumentNullException
Thrown when
valueorpredicateis 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
valuestringThe string to normalize. Must not be null.
newlinestringThe 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
valuehas been replaced bynewline. Whenvaluecontains 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
valueornewlineis null.
NullIfEmpty(string?)
public static string? NullIfEmpty(this string? value)
Parameters
valuestringThe string to evaluate.
Returns
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
valuestringThe string to evaluate.
Returns
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
valuestringThe source text. Must not be null.
countintThe maximum number of leading indent characters to remove per line. Must be non-negative.
indentCharcharThe 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
valueis null.- ArgumentOutOfRangeException
Thrown when
countis negative.
Parenthesize(string)
Returns value wrapped in round-bracket characters ((…)).
public static string Parenthesize(this string value)
Parameters
Returns
- string
The parenthesised string.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
Returns
- T
The parsed value.
Type Parameters
TThe target type, which must implement ISpanParsable<TSelf>.
Exceptions
- ArgumentNullException
Thrown when
valueis null.- FormatException
Thrown when
valueis not in a valid format forT.- OverflowException
Thrown when
valuerepresents a value outside the range supported byT.
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
Returns
- T
The parsed value.
Type Parameters
TThe 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
valueis null.- FormatException
Thrown when
valueis not in a valid format forT.- OverflowException
Thrown when
valuerepresents a value outside the range supported byT.
PrefixLines(string, string)
Returns value with prefix prepended to every line.
public static string PrefixLines(this string value, string prefix)
Parameters
valuestringThe source text. Must not be null.
prefixstringThe 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
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
valueis 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
valuestringThe string to inspect. Must not be null.
valueToRemovestringThe substring to remove. Must not be null or empty.
comparisonStringComparisonThe comparison rule used to locate occurrences of
valueToRemove. Defaults to Ordinal.
Returns
- string
A new string with the matches removed. When
valueToRemovedoes 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
valueorvalueToRemoveis null.- ArgumentException
Thrown when
valueToRemoveis the empty string.
RemoveControlCharacters(string)
Returns value with every Unicode control character removed.
public static string RemoveControlCharacters(this string value)
Parameters
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
valueis 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
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
valueis null.
RemoveDigits(string)
Returns value with every Unicode digit character removed.
public static string RemoveDigits(this string value)
Parameters
Returns
- string
A new string with digit characters stripped.
Exceptions
- ArgumentNullException
Thrown when
valueis null.
RemoveLineEndings(string)
Returns value with every carriage-return (\r) and line-feed (\n) character
removed.
public static string RemoveLineEndings(this string value)
Parameters
Returns
- string
A new string containing none of the
\ror\ncharacters fromvalue. Whenvaluealready 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
valueis 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
valuestringThe string to inspect. Must not be null.
valuesToRemovestring[]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
valuesToRemoveis empty, the original instance is returned unchanged.
Exceptions
- ArgumentNullException
Thrown when
valueorvaluesToRemoveis null, or when any element ofvaluesToRemoveis null.- ArgumentException
Thrown when any element of
valuesToRemoveis 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
valuestringThe string to inspect. Must not be null.
prefixstringThe prefix to remove. Must not be null.
comparisonStringComparisonThe comparison rule used to detect
prefixat the start ofvalue. Defaults to Ordinal.
Returns
- string
valuewithout the leadingprefixwhen 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
valueorprefixis null.
RemovePunctuation(string)
Returns value with every Unicode punctuation character removed.
public static string RemovePunctuation(this string value)
Parameters
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
valueis 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
valuestringThe string to inspect. Must not be null.
suffixstringThe suffix to remove. Must not be null.
comparisonStringComparisonThe comparison rule used to detect
suffixat the end ofvalue. Defaults to Ordinal.
Returns
- string
valuewithout the trailingsuffixwhen 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
valueorsuffixis null.
RemoveTrailingNewLine(string)
Returns value with a single trailing line ending removed when present.
public static string RemoveTrailingNewLine(this string value)
Parameters
Returns
- string
valuewith the last"\r\n","\n", or"\r"sequence removed. Returns the original instance unchanged whenvaluedoes 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
valueis 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
valuestringThe string to filter. Must not be null.
predicateFunc<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
valueorpredicateis null.
RemoveWhitespace(string)
Returns value with every white-space character removed.
public static string RemoveWhitespace(this string value)
Parameters
Returns
- string
A new string containing only the non-white-space characters from
value. Whenvaluealready 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
valueis 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
valuestringThe string to transform. Must not be null.
replacementsIReadOnlyDictionary<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
replacementsis 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
valueorreplacementsis null, or when any key inreplacementsis null.- ArgumentException
Thrown when any key in
replacementsis 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
valuestringThe string to search. Must not be null.
oldValuestringThe substring to replace. Must not be null or empty.
newValuestringThe replacement substring. May be null or empty.
Returns
- string
A new string with each case-insensitive occurrence of
oldValuereplaced.
Exceptions
- ArgumentNullException
Thrown when
valueoroldValueis null.- ArgumentException
Thrown when
oldValueis the empty string.
SingleQuote(string)
Returns value wrapped in straight single-quote characters ('…').
public static string SingleQuote(this string value)
Parameters
Returns
- string
The single-quoted string.
Remarks
This method does not escape embedded apostrophes.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe source string. Must not be null.
startIndexintThe 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 whenstartIndexis zero or negative; returns Empty whenstartIndexis greater than or equal tovalue.Length.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe source string. Must not be null.
startIndexintThe zero-based starting index. Negative values clamp to zero.
lengthintThe 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
startIndexof at mostlengthcharacters.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe string to split. Must not be null.
removeEmptyLinesboolWhen 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
valuewith 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
valueis 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
valuestringThe string to inspect. Must not be null.
valueToFindstringThe prefix to locate. Must not be null.
Returns
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
valueorvalueToFindis 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
valuestringThe string to inspect. Must not be null.
valueToFindstringThe prefix to locate. Must not be null.
Returns
- bool
true when
valuestarts withvalueToFindunder case-insensitive ordinal comparison; otherwise false.
Exceptions
- ArgumentNullException
Thrown when
valueorvalueToFindis 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
valuestringThe string to encode. Must not be null.
encodingEncodingThe text encoding used to convert
valueto 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
valueis 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
Returns
- string
The
camelCaseform ofvalue.
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
valueis null.
ToCamelCase(string, WordCasingOptions)
Converts value to camelCase under the supplied options.
public static string ToCamelCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
camelCaseform ofvalue.
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
valueoroptionsis null.
ToConstantCase(string)
Converts value to CONSTANT_CASE: upper-cased words joined by underscores.
public static string ToConstantCase(this string value)
Parameters
Returns
- string
The
CONSTANT_CASEform ofvalue.
Remarks
Word boundaries follow Bodu.Extensions.StringExtensions.EnumerateWords(System.String,Bodu.Extensions.WordCasingOptions) using Default. Every word is upper-cased.
Exceptions
- ArgumentNullException
Thrown when
valueis null.
ToConstantCase(string, WordCasingOptions)
Converts value to CONSTANT_CASE under the supplied options.
public static string ToConstantCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
CONSTANT_CASEform ofvalue.
Remarks
Every word, including acronyms, is upper-cased before joining.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis null.
ToDotCase(string)
Converts value to dot.case: lower-cased words joined by periods.
public static string ToDotCase(this string value)
Parameters
Returns
- string
The
dot.caseform ofvalue.
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
valueis null.
ToDotCase(string, WordCasingOptions)
Converts value to dot.case under the supplied options.
public static string ToDotCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
dot.caseform ofvalue.
Remarks
Every word, including acronyms, is lower-cased before joining.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis 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
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
valueis 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
valuestringThe string to convert.
identifierCaseIdentifierCaseThe 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
valueis null.- ArgumentOutOfRangeException
Thrown when
identifierCaseis 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
Returns
- string
The
kebab-caseform ofvalue.
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
valueis null.
ToKebabCase(string, WordCasingOptions)
Converts value to kebab-case under the supplied options.
public static string ToKebabCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
kebab-caseform ofvalue.
Remarks
Every word, including acronyms, is lower-cased before joining.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis 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
Returns
- string
The
PascalCaseform ofvalue.
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
valueis null.
ToPascalCase(string, WordCasingOptions)
Converts value to PascalCase under the supplied options.
public static string ToPascalCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
PascalCaseform ofvalue.
Remarks
Every word is capitalised unless it is a recognised mixed-case word, which is emitted verbatim.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis 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
valuestringThe 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
valueis 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
valuestringThe 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
valueis 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
Returns
- string
The sentence-case form of
value.
Exceptions
- ArgumentNullException
Thrown when
valueis null.
ToSentenceCase(string, SentenceCaseOptions)
Returns value in sentence case under the supplied options.
public static string ToSentenceCase(this string value, SentenceCaseOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsSentenceCaseOptionsFlags 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
valueis 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
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe 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
valueoroptionsis 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
Returns
- string
The slug form of
value.
Remarks
Equivalent to calling ToSlug(string, SlugOptions) with Default.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe string to convert. Must not be null.
optionsSlugOptionsThe 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
valueoroptionsis null.
ToSnakeCase(string)
Converts value to snake_case: lower-cased words joined by underscores.
public static string ToSnakeCase(this string value)
Parameters
Returns
- string
The
snake_caseform ofvalue.
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
valueis null.
ToSnakeCase(string, WordCasingOptions)
Converts value to snake_case under the supplied options.
public static string ToSnakeCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
snake_caseform ofvalue.
Remarks
Every word, including acronyms, is lower-cased before joining.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis 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
Returns
- string
The title-case form of
value.
Exceptions
- ArgumentNullException
Thrown when
valueis null.
ToTitleCase(string, TitleCaseOptions)
Returns value in title case under the supplied options.
public static string ToTitleCase(this string value, TitleCaseOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsTitleCaseOptionsFlags 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
valueis 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
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe 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
valueoroptionsis 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
Returns
- string
The
Train-Caseform ofvalue.
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
valueis null.
ToTrainCase(string, WordCasingOptions)
Converts value to Train-Case under the supplied options.
public static string ToTrainCase(this string value, WordCasingOptions options)
Parameters
valuestringThe string to convert. Must not be null.
optionsWordCasingOptionsThe acronym, mixed-case, and culture configuration. Must not be null.
Returns
- string
The
Train-Caseform ofvalue.
Remarks
Every word is capitalised unless it is a recognised mixed-case word, which is emitted verbatim.
Exceptions
- ArgumentNullException
Thrown when
valueoroptionsis null.
TrimOrEmpty(string?)
public static string TrimOrEmpty(this string? value)
Parameters
valuestringThe string to trim.
Returns
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?)
public static string? TrimToNull(this string? value)
Parameters
valuestringThe string to trim.
Returns
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
valuestringThe string to truncate. Must not be null.
maxLengthintThe maximum length to retain. Must be non-negative.
Returns
- string
valuewhen its length is at mostmaxLength; otherwise the firstmaxLengthcharacters.
Exceptions
- ArgumentNullException
Thrown when
valueis null.- ArgumentOutOfRangeException
Thrown when
maxLengthis 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
valuestringThe string to truncate. Must not be null.
maxLengthintThe maximum total length to retain, including
ellipsis. Must be at leastellipsis.Length.ellipsisstringThe suffix appended when truncation occurs. Must not be null.
Returns
- string
valuewhen its length is at mostmaxLength; otherwise the firstmaxLength - ellipsis.Lengthcharacters followed byellipsis.
Exceptions
- ArgumentNullException
Thrown when
valueorellipsisis null.- ArgumentOutOfRangeException
Thrown when
maxLengthis smaller thanellipsis.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
valuestringThe string to truncate. Must not be null.
maxLengthintThe maximum total length to retain, including
separator. Must be at leastseparator.Length.separatorstringThe marker inserted in place of the omitted middle. Defaults to the ellipsis character
"…". Must not be null.
Returns
- string
valuewhen its length is at mostmaxLength; otherwise a new string composed of the leading portion,separator, and the trailing portion ofvaluesuch that the total length equalsmaxLength. 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
valueorseparatoris null.- ArgumentOutOfRangeException
Thrown when
maxLengthis smaller thanseparator.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
valuestringThe string to parse.
resultTWhen this method returns true, contains the parsed value; otherwise the type's default value.
Returns
Type Parameters
TThe target type, which must implement ISpanParsable<TSelf>.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe string to parse.
resultTWhen this method returns true, contains the parsed value; otherwise the type's default value.
Returns
Type Parameters
TThe target type, which must implement IParsable<TSelf>.
Exceptions
- ArgumentNullException
Thrown when
valueis 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
valuestringThe source text. Must not be null.
prefixstringThe 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
valuestringThe string to unwrap. Must not be null.
prefixstringThe expected prefix. Must not be null.
suffixstringThe expected suffix. Must not be null.
comparisonStringComparisonThe string comparison used for prefix and suffix matching.
Returns
- string
The unwrapped string when both ends match; otherwise
valueunchanged. 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
valuestringThe string to wrap. Must not be null.
prefixstringThe string to prepend. Must not be null.
suffixstringThe string to append. Must not be null.
Returns
- string
The wrapped string.
Exceptions
- ArgumentNullException
Thrown when any argument is null.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |