PeanutButter
Loading...
Searching...
No Matches
PeanutButter.Utils.StringExtensions Class Reference

Provides utility extensions for strings. More...

Static Public Member Functions

static string RegexReplace (this string input, string pattern, string replaceWith)
 Replaces patterns matched by the given regex pattern with the given replaceWith string.
static string RegexReplaceAll (this string input, string replaceWith, params string[] patterns)
 Replace all matching regular expression strings in input with the given string.
static string RegexReplaceAll (this string input, string replaceWith, params Regex[] patterns)
 Replace all matching Regex patterns in input with the given string.
static string Or (this string input, string alternative)
 Convenience extension to return another string if the input is null or empty.
static bool AsBoolean (this string input)
 Attempts conversion from a string value to a boolean value matching the following (case-insensitive) to True:
static bool ContainsOneOf (this string haystack, params string[] needles)
 Searches a master string for occurrences of any of the given strings, case-insensitive.
static bool EqualsOneOf (this string haystack, params string[] needles)
 Much like ContainsOneOf, but performs a case-insensitive exact match for the needles against the haystack.
static bool ContainsAllOf (this string haystack, params string[] needles)
 Searches a master string for occurrences of any of the given strings.
static bool StartsWithOneOf (this string src, params string[] search)
 Tests if a string starts with one of the provided search strings.
static byte[] AsBytes (this string src)
 Calls AsBytes extension method with the UTF8 encoding.
static byte[] AsBytes (this string src, Encoding encoding)
 Convenience function to convert a string to a byte array.
static Stream AsStream (this string src)
 Converts a string to a Stream of bytes, assuming utf-8 encoding.
static IEnumerable< string > ToLower (this IEnumerable< string > src)
 Lowercases a string collection with Invariant culture. Tolerates nulls.
static IEnumerable< string > ToLower (this IEnumerable< string > src, CultureInfo cultureInfo)
 Lowercases a string collection with Invariant culture. Tolerates nulls.
static IEnumerable< string > ToUpper (this IEnumerable< string > src)
 Uppercases a string collection with Invariant culture. Tolerates nulls.
static IEnumerable< string > ToUpper (this IEnumerable< string > src, CultureInfo cultureInfo)
 Uppercases a string collection with Invariant culture. Tolerates nulls.
static Stream AsStream (this string src, Encoding encoding)
 Converts a string to a Stream of bytes with the provided encoding.
static string AsString (this byte[] data)
 Attempts to encode the given byte array as if it contained a utf8-encoded string.
static string AsString (this byte[] data, Encoding encoding)
 Attempts to encode the given byte array as if it contained a string encoded with the given encoding.
static Stream AsStream (this byte[] src)
 Convenience function to wrap a given byte array in a MemoryStream.
static bool IsInteger (this string src)
 Tests if a string represents an integer value.
static int AsInteger (this string value)
 Performs exceptionless conversion of a string to an integer.
static bool IsNullOrWhiteSpace (this string value)
 Turns string.IsNullOrWhiteSpace into an extension method for fluency.
static bool IsNullOrEmpty (this string value)
 Turns string.IsNullOrEmpty into an extension method for fluency.
static bool IsEmptyOrWhiteSpace (this string value)
 Tests if a string is empty or all whitespace NB: will return false for null.
static bool IsWhiteSpace (this string value)
 Tests if a string is non-empty, but made entirely of whitespace NB: will return false for null or empty string.
static string ToBase64 (this string value)
 Returns the base64-encoded representation of a string value.
static bool LooksLikeBase64 (this string str)
 Returns true if the string is non-empty and contains only base64-encoding characters.
static string ZeroIfEmptyOrNull (this string input)
 Returns "0" if the input string is empty or null.
static string DefaultIfEmptyOrNull (this string input, string fallback)
 Returns a given fallback value if the input string is whitespace or null.
static string SafeTrim (this string input, params char[] trimChars)
 Safely trims a string, returning an empty string if given null.
static string ToKebabCase (this string input)
 Converts an input string to kebab-case.
static string ReplaceAll (this string haystack, IEnumerable< char > needles, char replaceWith)
 Replace all occurrences of chars in needles with the replaceWith character.
static string ReplaceAll (this string haystack, IEnumerable< string > needles, string replaceWith)
 Replace all occurrences of strings in needles with the replaceWith string.
static string RemoveAll (this string subject, params char[] toRemove)
 Remove all the given characters from the string, returning a new string.
static string RemoveAll (this string subject, params string[] toRemove)
 Remove all the given substrings from the string, returning a new string.
static string ToSnakeCase (this string input)
 Converts an input string to snake_case.
static string ToPascalCase (this string input)
 Converts an input string to PascalCase.
static string ToTitleCase (this string input)
 Alias for ToPascalCase.
static string ToCamelCase (this string input)
 Converts an input string to camelCase.
static string ToRandomCase (this string input)
 Returns the input string in RaNdOMizEd case.
static string ToWords (this string input)
 Converts an input string to words, where possible eg: kebab-case => "kebab case" snake_case => "snake case" PascalCase => "pascal case".
static string[] ToWordsArray (this string input)
 Breaks a string into an array of words without any modifications on casing. Ported from lodash's unicodeWords.
static string ToLowerCasedFirstLetter (this string input)
 Lower-cases the first letter in your string.
static string ToUpperCasedFirstLetter (this string input)
 Upper-cases the first letter in your string.
static bool IsNumeric (this string str)
 Returns whether or not a string is an integer value.
static bool IsAlphanumeric (this string str)
 Tests if a string is Alphanumeric. Fails on null or whitespace too.
static bool IsAlpha (this string str)
 Tests if a string is Alphabetic only. Fails on null or whitespace too.
static bool IsNumeric (this char c)
 Tests if a character is numeric (0-9)
static bool IsAlpha (this char c)
 Tests if a character is alphabetic (a-z|A-Z)
static MemoryStream ToMemoryStream (this string str)
 Convenience wrapper to provide a memory stream around a string.
static string QuoteIfSpaced (this string str)
 Surrounds a string with quotes if it contains any whitespace.
static string[] SplitCommandline (this string str)
 Splits a commandline, respecting quoting.
static string DeQuote (this string str)
 "de-quotes" a string, only removes the outer-most, paired quotes, not just trimming, ie ""foo"" => "foo" "foo" => foo "foo => "foo
static bool Matches (this IEnumerable< string > left, IEnumerable< string > right, StringComparison comparison)
 tests if two string collections are identical, taking into account the provide comparison
static string Substr (this string str, int start)
 Returns the substring of the given string from the given start Tolerates a start outside of the string - will return empty string Tolerates a start < 0 - will start from the beginning of the string Tolerates null string - will return empty string.
static string Substr (this string str, int start, int length)
 Returns the substring of the given string from the given start with the provided length Tolerates a start after of the string - will return empty string Tolerates a start < 0 - will start from the beginning of the string Tolerates null string - will return empty string Tolerates a length out of bounds - will return all the string that it can Interprets a negative length as an offset from the end of the string.
static string Window (this string str, int centeredOn, int maxCharsLeftOrRight)
 Finds a window into a string, centered around the given centeredOn parameter, with maximum maxCharsLeftOrRight of the center. Eg: "12345".Window(2, 1) -> 234.
static string Window (this string str, int centeredOn, int maxCharsLeftOrRight, out int startedAt, out int endedAt)
 Finds a window into a string, centered around the given centeredOn parameter, with maximum maxCharsLeftOrRight of the center. Eg: "12345".Window(2, 1) -> 234.
static byte[] UnBase64 (this string base64Data)
 Converts a base64 string back to the original string.
static string UnBase64 (this string base64Data, Encoding encoding)
 Converts a base64 string back to the original string using the provided encoding.
static string UnBase64< T > (this string base64Data)
 Quick-decode for string base64 data T must be a string, ie var str = base64.UnBase64<string>()
static string UnBase64< T > (this string base64Data, Encoding encoding)
 Quick-decode for string base64 data using the provided encoding T must be a string, ie var str = base64.UnBase64<string>()
static T UnBase64< T > (this string base64Data, Func< string, T > deserializer)
 decode base64 string data & deserialize to type T
static T UnBase64< T > (this string base64Data, Func< byte[], T > deserializer)
 decode base64 string data & deserialize to type T
static T UnBase64< T > (this string base64Data, Func< string, T > deserializer, Encoding encoding)
 decode base64 string data & deserialize to type T, assuming that the original data in the base64 string was a string (eg json), using the provided encoding
static string Base64Padded (this string unpadded)
 Pads out a base64 string which is missing the base64 padding.
static string Base64UnPadded (this string base64Data)
 Removes base64 data padding (trailing '=' chars)
static string Outdent (this string str)
 Outdents a block to the first indentation.
static string Outdent (this string str, int depth)
 Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely.
static string[] SplitIntoLines (this string str)
 Splits text into lines, based on UNIX or DOS line endings, or a mixture of both.
static string[] MultiSplit (this string str, string delimiter, params string[] moreDelimiters)
 Splits a string based on one or more delimiters.
static string[] Outdent (this string[] lines, int depth)
 Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely. Attempts to determine the indent character from the first line with indenting.
static string[] Outdent (this string[] lines, string indentedWith, int depth, bool alsoTrimEnd)
 Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely.
static bool TryParseHex (this string str, out int parsed)
 Attempt to parse a string as an integer encoded with hex.
static string[] SplitOnce (this string str, string splitOn)
 Split the string only once, eg so "foo:bar:qux" split on ":" returns [ "foo", "bar:qux" ] edge cases: null returns empty array no delimiter -> array with single element (original string)
static string[] SplitPath (this string str)
 Splits a string as if it were a path, treating / and \ both as path delimiters.
static string[] SplitByRegex (this string str, string regex)
 Split a string by the provided C# regular expression.
static string[] SplitByRegex (this string str, string regex, RegexOptions options)
 Split a string by the provided C# regular expression with the provided regex options.
static string[] SplitByRegex (this string str, Regex regex)
 Split a string by the provided Regex.
static string ResolvePath (this string path, params string[] others)
 Resolves the result of a path containing .. and/or .
static bool IsAbsolutePath (this string str)
 Returns true if the given string looks like an absolute path, ie starts with one of:
static string RelativeTo (this string path, string basePath)
 Determine the relative path from the string being operated on to the one passed in. Eg, if operating on the path '/foo/bar', provided '/foo', the result is 'bar' The aim is to provide a C# analogue to Node's path.relative(...) Paths are treated automatically via this overload:
static string RelativeTo (this string path, string basePath, PathType pathType)
 Determine the relative path from the string being operated on to the one passed in. Eg, if operating on the path '/foo/bar', provided '/foo', the result is 'bar' The aim is to provide a C# analogue to Node's path.relative(...)
static string AsPlatformPath (this string path)
 Given a path in any format (unix or dos), returns the path normalised for the current OS.
static bool ContainsInOrder (this string haystack, params string[] needles)
 Tests that the provided strings (needles) are found in order within haystack, eg "foo bar quux".ContainsInOrder("foo", "quux"); // returns true.
static bool ContainsInOrder (this string haystack, StringComparison comparison, params string[] needles)
 Tests that the provided strings (needles) are found in order within haystack, using the provided comparison, eg "foo bar quux".ContainsInOrder(StringComparison.OrdinalIgnoreCase, "Foo", "qUUx"); // returns true.
static byte[] GZip (this string str)
 GZips the text as utf 8.
static byte[] GZip (this string str, Encoding encoding)
 GZips the text with the provided encoding.
static string AppendPath (this string start, params string[] parts)
 Appends the provided parts as path elements, using the path delimiter of the current platform, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie "foo/bar/".AppendPath("/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.
static string AppendWebPath (this string start, params string[] parts)
 Appends the provided parts as path elements, using a forward-slash, as per web paths, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie "foo/bar/".AppendPath("/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.
static string AppendPath (this string start, char delimiter, params string[] parts)
 Appends the provided parts as path elements, using the provided path delimiter, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie: "foo/bar/".AppendPath('/', "/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.
static string CondenseWhitespace (this string str)
 Condenses all whitespace in a string to single spaces.
static string CondenseWhitespace (this string str, string replaceWith)
 Condenses all whitespace in a string to the provided replacement.

Detailed Description

Provides utility extensions for strings.

Member Function Documentation

◆ AppendPath() [1/2]

string PeanutButter.Utils.StringExtensions.AppendPath ( this string start,
char delimiter,
params string[] parts )
static

Appends the provided parts as path elements, using the provided path delimiter, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie: "foo/bar/".AppendPath('/', "/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.

Parameters
start
delimiter
parts
Returns

◆ AppendPath() [2/2]

string PeanutButter.Utils.StringExtensions.AppendPath ( this string start,
params string[] parts )
static

Appends the provided parts as path elements, using the path delimiter of the current platform, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie "foo/bar/".AppendPath("/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.

Parameters
start
parts
Returns

◆ AppendWebPath()

string PeanutButter.Utils.StringExtensions.AppendWebPath ( this string start,
params string[] parts )
static

Appends the provided parts as path elements, using a forward-slash, as per web paths, ensuring only a single path delimiter between elements whilst retaining any initial leading delimiter and any trailing delimiter, ie "foo/bar/".AppendPath("/part0", "part1", "/part2/", "final/") should produce foo/bar/part0/part1/part2/final/.

Parameters
start
parts
Returns

◆ AsBoolean()

bool PeanutButter.Utils.StringExtensions.AsBoolean ( this string input)
static

Attempts conversion from a string value to a boolean value matching the following (case-insensitive) to True:

  • "yes"
  • "y"
  • "1"
  • "true" All other string values are considered to be false
Parameters
inputString to attempt to convert
Returns
True for truthy values, False otherwise

◆ AsBytes() [1/2]

byte[] PeanutButter.Utils.StringExtensions.AsBytes ( this string src)
static

Calls AsBytes extension method with the UTF8 encoding.

Parameters
srcString to operate on
Returns
Byte array representing string, from UTF8 encoding

◆ AsBytes() [2/2]

byte[] PeanutButter.Utils.StringExtensions.AsBytes ( this string src,
Encoding encoding )
static

Convenience function to convert a string to a byte array.

Parameters
srcString to convert
encodingEncoding to use
Returns
Byte array of the {src} string when decoded as UTF-8

◆ AsInteger()

int PeanutButter.Utils.StringExtensions.AsInteger ( this string value)
static

Performs exceptionless conversion of a string to an integer.

Parameters
valueString to convert
Returns
The integer value of the string; 0 if it cannot be converted

◆ AsPlatformPath()

string PeanutButter.Utils.StringExtensions.AsPlatformPath ( this string path)
static

Given a path in any format (unix or dos), returns the path normalised for the current OS.

Parameters
path
Returns

◆ AsStream() [1/3]

Stream PeanutButter.Utils.StringExtensions.AsStream ( this byte[] src)
static

Convenience function to wrap a given byte array in a MemoryStream.

Parameters
srcBytes to wrapp
Returns
Stream wrapping the bytes or null if the source is null

◆ AsStream() [2/3]

Stream PeanutButter.Utils.StringExtensions.AsStream ( this string src)
static

Converts a string to a Stream of bytes, assuming utf-8 encoding.

Parameters
srcString to convert
Returns
Stream or null if src is null

◆ AsStream() [3/3]

Stream PeanutButter.Utils.StringExtensions.AsStream ( this string src,
Encoding encoding )
static

Converts a string to a Stream of bytes with the provided encoding.

Parameters
srcString to convert
encodingEncoding to use
Returns
Stream or null if src is null

◆ AsString() [1/2]

string PeanutButter.Utils.StringExtensions.AsString ( this byte[] data)
static

Attempts to encode the given byte array as if it contained a utf8-encoded string.

Parameters
dataBytes to encode
Returns
The utf8 string, if possible; will return null if given null

◆ AsString() [2/2]

string PeanutButter.Utils.StringExtensions.AsString ( this byte[] data,
Encoding encoding )
static

Attempts to encode the given byte array as if it contained a string encoded with the given encoding.

Parameters
dataBytes to encode
encoding
Returns
The string, if possible; will return null if given null

◆ Base64Padded()

string PeanutButter.Utils.StringExtensions.Base64Padded ( this string unpadded)
static

Pads out a base64 string which is missing the base64 padding.

Parameters
unpadded
Returns

◆ Base64UnPadded()

string PeanutButter.Utils.StringExtensions.Base64UnPadded ( this string base64Data)
static

Removes base64 data padding (trailing '=' chars)

Parameters
base64Data
Returns

◆ CondenseWhitespace() [1/2]

string PeanutButter.Utils.StringExtensions.CondenseWhitespace ( this string str)
static

Condenses all whitespace in a string to single spaces.

Parameters
str
Returns

◆ CondenseWhitespace() [2/2]

string PeanutButter.Utils.StringExtensions.CondenseWhitespace ( this string str,
string replaceWith )
static

Condenses all whitespace in a string to the provided replacement.

Parameters
str
replaceWith
Returns

◆ ContainsAllOf()

bool PeanutButter.Utils.StringExtensions.ContainsAllOf ( this string haystack,
params string[] needles )
static

Searches a master string for occurrences of any of the given strings.

Parameters
haystackString to search
needlesStrings to search for
Returns
True if all of the needles are found in the haystack; False otherwise

◆ ContainsInOrder() [1/2]

bool PeanutButter.Utils.StringExtensions.ContainsInOrder ( this string haystack,
params string[] needles )
static

Tests that the provided strings (needles) are found in order within haystack, eg "foo bar quux".ContainsInOrder("foo", "quux"); // returns true.

Parameters
haystackmaster string to search
needlessubstrings to search for
Returns

◆ ContainsInOrder() [2/2]

bool PeanutButter.Utils.StringExtensions.ContainsInOrder ( this string haystack,
StringComparison comparison,
params string[] needles )
static

Tests that the provided strings (needles) are found in order within haystack, using the provided comparison, eg "foo bar quux".ContainsInOrder(StringComparison.OrdinalIgnoreCase, "Foo", "qUUx"); // returns true.

Parameters
haystackmaster string to search
comparison
needlessubstrings to search for
Returns

◆ ContainsOneOf()

bool PeanutButter.Utils.StringExtensions.ContainsOneOf ( this string haystack,
params string[] needles )
static

Searches a master string for occurrences of any of the given strings, case-insensitive.

Parameters
haystackString to search
needlesStrings to search for
Returns
True if any of the needles are found in the haystack; False otherwise

◆ DefaultIfEmptyOrNull()

string PeanutButter.Utils.StringExtensions.DefaultIfEmptyOrNull ( this string input,
string fallback )
static

Returns a given fallback value if the input string is whitespace or null.

Parameters
inputString to test
fallbackFallback value if the input is whitespace or null
Returns
Original string or the given fallback if the input is whitespace or null

◆ DeQuote()

string PeanutButter.Utils.StringExtensions.DeQuote ( this string str)
static

"de-quotes" a string, only removes the outer-most, paired quotes, not just trimming, ie ""foo"" => "foo" "foo" => foo "foo => "foo

Parameters
str
Returns

◆ EqualsOneOf()

bool PeanutButter.Utils.StringExtensions.EqualsOneOf ( this string haystack,
params string[] needles )
static

Much like ContainsOneOf, but performs a case-insensitive exact match for the needles against the haystack.

Parameters
haystack
needles
Returns

◆ GZip() [1/2]

byte[] PeanutButter.Utils.StringExtensions.GZip ( this string str)
static

GZips the text as utf 8.

Parameters
str
Returns

◆ GZip() [2/2]

byte[] PeanutButter.Utils.StringExtensions.GZip ( this string str,
Encoding encoding )
static

GZips the text with the provided encoding.

Parameters
str
encoding
Returns

◆ IsAbsolutePath()

bool PeanutButter.Utils.StringExtensions.IsAbsolutePath ( this string str)
static

Returns true if the given string looks like an absolute path, ie starts with one of:

  • /
  • \
  • windows drive (eg C:)
Parameters
str
Returns

◆ IsAlpha() [1/2]

bool PeanutButter.Utils.StringExtensions.IsAlpha ( this char c)
static

Tests if a character is alphabetic (a-z|A-Z)

Parameters
c
Returns

◆ IsAlpha() [2/2]

bool PeanutButter.Utils.StringExtensions.IsAlpha ( this string str)
static

Tests if a string is Alphabetic only. Fails on null or whitespace too.

Parameters
str
Returns

◆ IsAlphanumeric()

bool PeanutButter.Utils.StringExtensions.IsAlphanumeric ( this string str)
static

Tests if a string is Alphanumeric. Fails on null or whitespace too.

Parameters
str
Returns

◆ IsEmptyOrWhiteSpace()

bool PeanutButter.Utils.StringExtensions.IsEmptyOrWhiteSpace ( this string value)
static

Tests if a string is empty or all whitespace NB: will return false for null.

Parameters
value
Returns

◆ IsInteger()

bool PeanutButter.Utils.StringExtensions.IsInteger ( this string src)
static

Tests if a string represents an integer value.

Parameters
srcString to test
Returns
True if the string can be converted to an integer; False otherwise

◆ IsNullOrEmpty()

bool PeanutButter.Utils.StringExtensions.IsNullOrEmpty ( this string value)
static

Turns string.IsNullOrEmpty into an extension method for fluency.

Parameters
valueString to test
Returns
True if is null or whitespace; False otherwise

◆ IsNullOrWhiteSpace()

bool PeanutButter.Utils.StringExtensions.IsNullOrWhiteSpace ( this string value)
static

Turns string.IsNullOrWhiteSpace into an extension method for fluency.

Parameters
valueString to test
Returns
True if is null or whitespace; False otherwise

◆ IsNumeric() [1/2]

bool PeanutButter.Utils.StringExtensions.IsNumeric ( this char c)
static

Tests if a character is numeric (0-9)

Parameters
c
Returns

◆ IsNumeric() [2/2]

bool PeanutButter.Utils.StringExtensions.IsNumeric ( this string str)
static

Returns whether or not a string is an integer value.

Parameters
strstring to test
Returns

◆ IsWhiteSpace()

bool PeanutButter.Utils.StringExtensions.IsWhiteSpace ( this string value)
static

Tests if a string is non-empty, but made entirely of whitespace NB: will return false for null or empty string.

Parameters
value
Returns

◆ LooksLikeBase64()

bool PeanutButter.Utils.StringExtensions.LooksLikeBase64 ( this string str)
static

Returns true if the string is non-empty and contains only base64-encoding characters.

Parameters
str
Returns

◆ Matches()

bool PeanutButter.Utils.StringExtensions.Matches ( this IEnumerable< string > left,
IEnumerable< string > right,
StringComparison comparison )
static

tests if two string collections are identical, taking into account the provide comparison

Parameters
left
right
comparison
Returns
true if collections are of the same size and each item, in order, from the left item, matches the right one

◆ MultiSplit()

string[] PeanutButter.Utils.StringExtensions.MultiSplit ( this string str,
string delimiter,
params string[] moreDelimiters )
static

Splits a string based on one or more delimiters.

Parameters
str
delimiter
moreDelimiters
Returns

◆ Or()

string PeanutButter.Utils.StringExtensions.Or ( this string input,
string alternative )
static

Convenience extension to return another string if the input is null or empty.

Parameters
inputString to test
alternativeString to return if the input was null or empty
Returns
The original string when it is not null or empty; the alternative when the original is null or empty

◆ Outdent() [1/4]

string PeanutButter.Utils.StringExtensions.Outdent ( this string str)
static

Outdents a block to the first indentation.

Parameters
strstring to outdent
Returns

◆ Outdent() [2/4]

string PeanutButter.Utils.StringExtensions.Outdent ( this string str,
int depth )
static

Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely.

Parameters
strstring to outdent
depthdepth to outdent to
Returns

◆ Outdent() [3/4]

string[] PeanutButter.Utils.StringExtensions.Outdent ( this string[] lines,
int depth )
static

Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely. Attempts to determine the indent character from the first line with indenting.

Parameters
lines
depthdepth to outdent to
Returns

◆ Outdent() [4/4]

string[] PeanutButter.Utils.StringExtensions.Outdent ( this string[] lines,
string indentedWith,
int depth,
bool alsoTrimEnd )
static

Outdents a block of text at most to the given depth. Will stop as soon as any line is outdented completely.

Parameters
lines
indentedWith
depth
alsoTrimEndalso right-trim lines, much like an auto-formatter would
Returns

◆ QuoteIfSpaced()

string PeanutButter.Utils.StringExtensions.QuoteIfSpaced ( this string str)
static

Surrounds a string with quotes if it contains any whitespace.

Parameters
str
Returns

◆ RegexReplace()

string PeanutButter.Utils.StringExtensions.RegexReplace ( this string input,
string pattern,
string replaceWith )
static

Replaces patterns matched by the given regex pattern with the given replaceWith string.

Parameters
inputStarting string
patternRegex pattern to search for
replaceWithString to replace occurrences with
Returns
New string with matches replaces

◆ RegexReplaceAll() [1/2]

string PeanutButter.Utils.StringExtensions.RegexReplaceAll ( this string input,
string replaceWith,
params Regex[] patterns )
static

Replace all matching Regex patterns in input with the given string.

Parameters
input
replaceWith
patterns
Returns

◆ RegexReplaceAll() [2/2]

string PeanutButter.Utils.StringExtensions.RegexReplaceAll ( this string input,
string replaceWith,
params string[] patterns )
static

Replace all matching regular expression strings in input with the given string.

Parameters
input
replaceWith
patterns
Returns

◆ RelativeTo() [1/2]

string PeanutButter.Utils.StringExtensions.RelativeTo ( this string path,
string basePath )
static

Determine the relative path from the string being operated on to the one passed in. Eg, if operating on the path '/foo/bar', provided '/foo', the result is 'bar' The aim is to provide a C# analogue to Node's path.relative(...) Paths are treated automatically via this overload:

  • split on any path delimiter (/ or )
  • compared case-insensitive on windows, case-sensitive elsewhere
Parameters
path
basePath
Returns

◆ RelativeTo() [2/2]

string PeanutButter.Utils.StringExtensions.RelativeTo ( this string path,
string basePath,
PathType pathType )
static

Determine the relative path from the string being operated on to the one passed in. Eg, if operating on the path '/foo/bar', provided '/foo', the result is 'bar' The aim is to provide a C# analogue to Node's path.relative(...)

Parameters
path
basePath
pathType
Returns

◆ RemoveAll() [1/2]

string PeanutButter.Utils.StringExtensions.RemoveAll ( this string subject,
params char[] toRemove )
static

Remove all the given characters from the string, returning a new string.

Parameters
subject
toRemove
Returns

◆ RemoveAll() [2/2]

string PeanutButter.Utils.StringExtensions.RemoveAll ( this string subject,
params string[] toRemove )
static

Remove all the given substrings from the string, returning a new string.

Parameters
subject
toRemove
Returns

◆ ReplaceAll() [1/2]

string PeanutButter.Utils.StringExtensions.ReplaceAll ( this string haystack,
IEnumerable< char > needles,
char replaceWith )
static

Replace all occurrences of chars in needles with the replaceWith character.

Parameters
haystack
needles
replaceWith
Returns

◆ ReplaceAll() [2/2]

string PeanutButter.Utils.StringExtensions.ReplaceAll ( this string haystack,
IEnumerable< string > needles,
string replaceWith )
static

Replace all occurrences of strings in needles with the replaceWith string.

Parameters
haystack
needles
replaceWith
Returns

◆ ResolvePath()

string PeanutButter.Utils.StringExtensions.ResolvePath ( this string path,
params string[] others )
static

Resolves the result of a path containing .. and/or .

Parameters
path
others
Returns

◆ SafeTrim()

string PeanutButter.Utils.StringExtensions.SafeTrim ( this string input,
params char[] trimChars )
static

Safely trims a string, returning an empty string if given null.

Parameters
inputString to trim
trimCharsOptional params of chars to trim, passed to standard String.Trim() method
Returns
Empty string if input is null, otherwise trimmed input

◆ SplitByRegex() [1/3]

string[] PeanutButter.Utils.StringExtensions.SplitByRegex ( this string str,
Regex regex )
static

Split a string by the provided Regex.

Parameters
str
regex
Returns

◆ SplitByRegex() [2/3]

string[] PeanutButter.Utils.StringExtensions.SplitByRegex ( this string str,
string regex )
static

Split a string by the provided C# regular expression.

Parameters
str
regex
Returns

◆ SplitByRegex() [3/3]

string[] PeanutButter.Utils.StringExtensions.SplitByRegex ( this string str,
string regex,
RegexOptions options )
static

Split a string by the provided C# regular expression with the provided regex options.

Parameters
str
regex
options
Returns

◆ SplitCommandline()

string[] PeanutButter.Utils.StringExtensions.SplitCommandline ( this string str)
static

Splits a commandline, respecting quoting.

Parameters
str
Returns

◆ SplitIntoLines()

string[] PeanutButter.Utils.StringExtensions.SplitIntoLines ( this string str)
static

Splits text into lines, based on UNIX or DOS line endings, or a mixture of both.

Parameters
str
Returns
Exceptions
NotImplementedException

◆ SplitOnce()

string[] PeanutButter.Utils.StringExtensions.SplitOnce ( this string str,
string splitOn )
static

Split the string only once, eg so "foo:bar:qux" split on ":" returns [ "foo", "bar:qux" ] edge cases: null returns empty array no delimiter -> array with single element (original string)

Parameters
str
splitOn
Returns

◆ SplitPath()

string[] PeanutButter.Utils.StringExtensions.SplitPath ( this string str)
static

Splits a string as if it were a path, treating / and \ both as path delimiters.

Parameters
str
Returns

◆ StartsWithOneOf()

bool PeanutButter.Utils.StringExtensions.StartsWithOneOf ( this string src,
params string[] search )
static

Tests if a string starts with one of the provided search strings.

Parameters
srcString to test
searchStrings to look for at the start of {src}
Returns
True if {src} starts with any one of provided search strings; False otherwise

◆ Substr() [1/2]

string PeanutButter.Utils.StringExtensions.Substr ( this string str,
int start )
static

Returns the substring of the given string from the given start Tolerates a start outside of the string - will return empty string Tolerates a start < 0 - will start from the beginning of the string Tolerates null string - will return empty string.

Parameters
strstring to operate on
startdesired starting point
Returns

◆ Substr() [2/2]

string PeanutButter.Utils.StringExtensions.Substr ( this string str,
int start,
int length )
static

Returns the substring of the given string from the given start with the provided length Tolerates a start after of the string - will return empty string Tolerates a start < 0 - will start from the beginning of the string Tolerates null string - will return empty string Tolerates a length out of bounds - will return all the string that it can Interprets a negative length as an offset from the end of the string.

Parameters
str
start
length
Returns

◆ ToBase64()

string PeanutButter.Utils.StringExtensions.ToBase64 ( this string value)
static

Returns the base64-encoded representation of a string value.

Parameters
valueInput string value
Returns
The base64-encoded representation of the string, or null if the string is null

◆ ToCamelCase()

string PeanutButter.Utils.StringExtensions.ToCamelCase ( this string input)
static

Converts an input string to camelCase.

Parameters
inputstring to convert
Returns
camelCasedOutput

◆ ToKebabCase()

string PeanutButter.Utils.StringExtensions.ToKebabCase ( this string input)
static

Converts an input string to kebab-case.

Parameters
inputstring to convert
Returns
kebab-cased-output

◆ ToLower() [1/2]

IEnumerable< string > PeanutButter.Utils.StringExtensions.ToLower ( this IEnumerable< string > src)
static

Lowercases a string collection with Invariant culture. Tolerates nulls.

Parameters
srcCollection to lower-case
Returns
Input, lower-cased

◆ ToLower() [2/2]

IEnumerable< string > PeanutButter.Utils.StringExtensions.ToLower ( this IEnumerable< string > src,
CultureInfo cultureInfo )
static

Lowercases a string collection with Invariant culture. Tolerates nulls.

Parameters
srcCollection to lower-case
cultureInfoCulture to use in the operation
Returns
Input, lower-cased

◆ ToLowerCasedFirstLetter()

string PeanutButter.Utils.StringExtensions.ToLowerCasedFirstLetter ( this string input)
static

Lower-cases the first letter in your string.

Parameters
inputstring to operate on
Returns
string with lower-cased first letter or null if input was null

◆ ToMemoryStream()

MemoryStream PeanutButter.Utils.StringExtensions.ToMemoryStream ( this string str)
static

Convenience wrapper to provide a memory stream around a string.

Parameters
str
Returns

◆ ToPascalCase()

string PeanutButter.Utils.StringExtensions.ToPascalCase ( this string input)
static

Converts an input string to PascalCase.

Parameters
inputstring to convert
Returns
  • pascalCasedOutput => PascalCasedOutput
  • pascal-cased-output => PascalCasedOutput
  • pascal_cased_output => PascalCasedOutput
  • pascal cased output => Pascal Cased Output

◆ ToRandomCase()

string PeanutButter.Utils.StringExtensions.ToRandomCase ( this string input)
static

Returns the input string in RaNdOMizEd case.

Parameters
input
Returns

◆ ToSnakeCase()

string PeanutButter.Utils.StringExtensions.ToSnakeCase ( this string input)
static

Converts an input string to snake_case.

Parameters
inputstring to convert
Returns
snake_cased_output

◆ ToTitleCase()

string PeanutButter.Utils.StringExtensions.ToTitleCase ( this string input)
static

Alias for ToPascalCase.

Parameters
input
Returns

◆ ToUpper() [1/2]

IEnumerable< string > PeanutButter.Utils.StringExtensions.ToUpper ( this IEnumerable< string > src)
static

Uppercases a string collection with Invariant culture. Tolerates nulls.

Parameters
srcCollection to lower-case
Returns
Input, lower-cased

◆ ToUpper() [2/2]

IEnumerable< string > PeanutButter.Utils.StringExtensions.ToUpper ( this IEnumerable< string > src,
CultureInfo cultureInfo )
static

Uppercases a string collection with Invariant culture. Tolerates nulls.

Parameters
srcCollection to lower-case
cultureInfoCulture to use in the operation. Note that .NET's ToUpper doesn't accept a culture, so really, your only choices here are "Invariant" or "whatever .Net uses by default".
Returns
Input, lower-cased

◆ ToUpperCasedFirstLetter()

string PeanutButter.Utils.StringExtensions.ToUpperCasedFirstLetter ( this string input)
static

Upper-cases the first letter in your string.

Parameters
inputstring to operate on
Returns
string with upper-cased first letter or null if input was null

◆ ToWords()

string PeanutButter.Utils.StringExtensions.ToWords ( this string input)
static

Converts an input string to words, where possible eg: kebab-case => "kebab case" snake_case => "snake case" PascalCase => "pascal case".

Parameters
input
Returns

◆ ToWordsArray()

string[] PeanutButter.Utils.StringExtensions.ToWordsArray ( this string input)
static

Breaks a string into an array of words without any modifications on casing. Ported from lodash's unicodeWords.

Parameters
input
Returns

◆ TryParseHex()

bool PeanutButter.Utils.StringExtensions.TryParseHex ( this string str,
out int parsed )
static

Attempt to parse a string as an integer encoded with hex.

Parameters
str
parsed
Returns

◆ UnBase64() [1/2]

byte[] PeanutButter.Utils.StringExtensions.UnBase64 ( this string base64Data)
static

Converts a base64 string back to the original string.

  • assumes the original string is UTF8
Parameters
base64Data
Returns

◆ UnBase64() [2/2]

string PeanutButter.Utils.StringExtensions.UnBase64 ( this string base64Data,
Encoding encoding )
static

Converts a base64 string back to the original string using the provided encoding.

Parameters
base64Data
encoding
Returns

◆ UnBase64< T >() [1/5]

string PeanutButter.Utils.StringExtensions.UnBase64< T > ( this string base64Data)
static

Quick-decode for string base64 data T must be a string, ie var str = base64.UnBase64<string>()

  • assumes UTF8 encoding
Parameters
base64Data
Template Parameters
T
Returns

◆ UnBase64< T >() [2/5]

string PeanutButter.Utils.StringExtensions.UnBase64< T > ( this string base64Data,
Encoding encoding )
static

Quick-decode for string base64 data using the provided encoding T must be a string, ie var str = base64.UnBase64<string>()

Parameters
base64Data
encoding
Template Parameters
T
Returns

◆ UnBase64< T >() [3/5]

T PeanutButter.Utils.StringExtensions.UnBase64< T > ( this string base64Data,
Func< byte[], T > deserializer )
static

decode base64 string data & deserialize to type T

Parameters
base64Data
deserializer
Template Parameters
T
Returns

◆ UnBase64< T >() [4/5]

T PeanutButter.Utils.StringExtensions.UnBase64< T > ( this string base64Data,
Func< string, T > deserializer )
static

decode base64 string data & deserialize to type T

Parameters
base64Data
deserializer
Template Parameters
T
Returns

◆ UnBase64< T >() [5/5]

T PeanutButter.Utils.StringExtensions.UnBase64< T > ( this string base64Data,
Func< string, T > deserializer,
Encoding encoding )
static

decode base64 string data & deserialize to type T, assuming that the original data in the base64 string was a string (eg json), using the provided encoding

Parameters
base64Data
deserializer
encoding
Template Parameters
T
Returns

◆ Window() [1/2]

string PeanutButter.Utils.StringExtensions.Window ( this string str,
int centeredOn,
int maxCharsLeftOrRight )
static

Finds a window into a string, centered around the given centeredOn parameter, with maximum maxCharsLeftOrRight of the center. Eg: "12345".Window(2, 1) -> 234.

Parameters
str
centeredOn
maxCharsLeftOrRight
Returns

◆ Window() [2/2]

string PeanutButter.Utils.StringExtensions.Window ( this string str,
int centeredOn,
int maxCharsLeftOrRight,
out int startedAt,
out int endedAt )
static

Finds a window into a string, centered around the given centeredOn parameter, with maximum maxCharsLeftOrRight of the center. Eg: "12345".Window(2, 1) -> 234.

Parameters
str
centeredOn
maxCharsLeftOrRight
startedAt
endedAt
Returns

◆ ZeroIfEmptyOrNull()

string PeanutButter.Utils.StringExtensions.ZeroIfEmptyOrNull ( this string input)
static

Returns "0" if the input string is empty or null.

Parameters
inputString to test
Returns
Original string or "0" if empty or null

The documentation for this class was generated from the following file:
  • source/Utils/PeanutButter.Utils/StringExtensions.cs