Skip to content

String Extensions

Andrzej Kebab edited this page Jan 23, 2024 · 4 revisions

UtilityLibrary.Core

This C# utility library provides a set of extension methods for string manipulation and conversion. Below is a list of available extension methods categorized by their functionality.

Null / Empty / WhiteSpace

  • IsNullOrEmpty: Checks if the string is null or empty.
  • IsNotNullOrEmpty: Checks if the string is not null or empty.
  • IsEmptyOrWhiteSpace: Checks if the string is empty or contains only white-space characters.
  • IsNotEmptyOrWhiteSpace: Checks if the string is not empty and does not contain only white-space characters.
  • IfEmptyOrWhiteSpace: Returns the string if it is not empty and does not contain only white-space characters; otherwise, returns the default value.

Examples:

string str = "example";
bool isNullOrEmpty = str.IsNullOrEmpty(); // Returns false
bool isWhiteSpace = str.IsEmptyOrWhiteSpace(); // Returns false
bool isValidOrDefault = str.IfEmptyOrWhiteSpace("default"); // Returns "example"

Convert To

  • IsBoolean: Checks if the string can be converted to a boolean.
  • AsBoolean: Converts the string to a boolean.
  • IsShort: Checks if the string can be converted to a short.
  • AsShort: Converts the string to a short.
  • IsInt: Checks if the string can be converted to an integer.
  • AsInt: Converts the string to an integer.
  • IsLong: Checks if the string can be converted to a long.
  • AsLong: Converts the string to a long.
  • IsFloat: Checks if the string can be converted to a float.
  • AsFloat: Converts the string to a float.
  • IsDouble: Checks if the string can be converted to a double.
  • AsDouble: Converts the string to a double.
  • IsDecimal: Checks if the string can be converted to a decimal.
  • AsDecimal: Converts the string to a decimal.

Examples:

string numericStr = "123";
bool isInt = numericStr.IsInt(); // Returns true
int intValue = numericStr.AsInt(); // Returns 123

Trim

  • TrimToMaxLength: Trims the string to a maximum length.
  • TrimToMaxLength: Trims the string to a maximum length and appends a suffix if it exceeds the maximum length.

Examples:

string longStr = "This is a very long string";
string trimmedStr = longStr.TrimToMaxLength(10); // Returns "This is a"
string trimmedWithSuffix = longStr.TrimToMaxLength(10, "..."); // Returns "This is a..."

Contains

  • Contains: Determines whether a string contains a specified substring with a specified string comparison.
  • ContainsAny: Determines whether a string contains any of the specified substrings.
  • ContainsAny: Determines whether a string contains any of the specified substrings with a specified string comparison.
  • ContainsAll: Determines whether a string contains all of the specified substrings.
  • ContainsAll: Determines whether a string contains all of the specified substrings with a specified string comparison.
  • EqualsAny: Determines whether a string equals any of the specified strings with a specified string comparison.

Examples:

string text = "Hello, world!";
bool containsHello = text.Contains("Hello", StringComparison.OrdinalIgnoreCase); // Returns true
bool containsAny = text.ContainsAny(StringComparison.OrdinalIgnoreCase, "hello", "foo"); // Returns true
bool containsAll = text.ContainsAll(StringComparison.OrdinalIgnoreCase, "hello", "world"); // Returns true

Remove

  • Remove: Removes all occurrences of the specified characters from the string.
  • Remove: Removes all occurrences of the specified strings from the string.

Examples:

string originalStr = "This is a sample string";
string removedChars = originalStr.Remove('i', 's'); // Returns "Th a ample trng"
string removedStrings = originalStr.Remove("sample", "is"); // Returns "Th  a  trng"

Replace

  • ReplaceAll: Replaces all occurrences of a set of strings with another specified string.
  • ReplaceAll: Replaces all occurrences of a set of strings with a set of replacement strings.
  • ReplaceWith: Replaces all strings that match a specified regular expression with a specified replacement string.
  • ReplaceWith: Replaces all strings that match a specified regular expression with a specified replacement string and options.

Examples:

string textToReplace = "This is a sample text";
IEnumerable<string> oldValues = new List<string> { "sample", "is" };
string replacedText = textToReplace.ReplaceAll(oldValues, "new"); // Returns "Thnew a new text"
string regexPattern = @"\s";
string replacedSpaces = textToReplace.ReplaceWith(regexPattern, "_"); // Returns "This_is_a_sample_text"

Format

  • ToUpperFirstLetter: Converts the first character of the string to uppercase.
  • ToTitleCase: Converts the string to title case using the current culture.
  • ToTitleCase: Converts the string to title case using the specified culture.
  • SpaceOnUpper: Inserts a space before each uppercase character in the string.

Examples:

string strToFormat = "example string";
string upperFirstLetter = strToFormat.ToUpperFirstLetter(); // Returns "Example string"
string titleCase = strToFormat.ToTitleCase(); // Returns "Example String"
string spacedOnUpper = strToFormat.SpaceOnUpper(); // Returns "example String"

Like

  • IsLikeAny: Checks if the string matches any of the provided patterns.
  • IsLike: Checks if the string matches the provided pattern.

Examples:

string strToMatch = "example";
bool isLikeAny = strToMatch.IsLikeAny("ex*", "foo"); // Returns true
bool isLike = strToMatch.IsLike("ex*mple"); // Returns true

Check Type

  • IsNumber: Checks if the string represents a number.

Examples:

string numericStr = "123";
bool isNumber = numericStr.IsNumber(); // Returns true

Reverse

  • Reverse: Reverses the order of the characters in the string.

Examples:

string strToReverse = "example";
string reversedStr = strToReverse.Reverse(); // Returns "elpmaxe"

Regex

IsMatch(string pattern)

Checks if the string matches the given pattern.

// Example usage with a string
string stringValue = "Hello123";
bool isMatch = stringValue.IsMatch("^[A-Za-z]+$");
Console.WriteLine($"Is match: {isMatch}");
// Output: Is match: False

Parameters:

  • value (string): The string to check.
  • pattern (string): The pattern to match.

Returns:

  • bool: True if the string matches the pattern, false otherwise.

IsMatch(Regex regex)

Checks if the string matches the given Regex.

// Example usage with a string
string stringValue = "Hello123";
Regex regex = new Regex("^[A-Za-z]+$");
bool isMatch = stringValue.IsMatch(regex);
Console.WriteLine($"Is match: {isMatch}");
// Output: Is match: False

Parameters:

  • value (string): The string to check.
  • regex (Regex): The Regex to match.

Returns:

  • bool: True if the string matches the Regex, false otherwise.

Match(string pattern)

Returns the first match of the pattern in the string.

// Example usage with a string
string stringValue = "Hello123";
string matchValue = stringValue.Match("\\d+");
Console.WriteLine($"Match value: {matchValue}");
// Output: Match value: 123

Parameters:

  • value (string): The string to search.
  • pattern (string): The pattern to match.

Returns:

  • string: The first match of the pattern in the string.

Match(Regex regex)

Returns the first match of the Regex in the string.

// Example usage with a string
string stringValue = "Hello123";
Regex regex = new Regex("\\d+");
string matchValue = stringValue.Match(regex);
Console.WriteLine($"Match value: {matchValue}");
// Output: Match value: 123

Parameters:

  • value (string): The string to search.
  • regex (Regex): The Regex to match.

Returns:

  • string: The first match of the Regex in the string.

Matches(string regexPattern)

Returns all matches of the pattern in the string.

// Example usage with a string
string stringValue = "abc123def456";
MatchCollection matches = stringValue.Matches("\\d+");
Console.WriteLine($"Number of matches: {matches.Count}");
// Output: Number of matches: 2

Parameters:

  • value (string): The string to search.
  • regexPattern (string): The pattern to match.

Returns:

  • MatchCollection: All matches of the pattern in the string.

Matches(string regexPattern, RegexOptions options)

Returns all matches of the pattern in the string with the specified options.

// Example usage with a string
string stringValue = "abc123def456";
MatchCollection matches = stringValue.Matches("\\d+", RegexOptions.IgnoreCase);
Console.WriteLine($"Number of matches: {matches.Count}");
// Output: Number of matches: 2

Parameters:

  • value (string): The string to search.
  • regexPattern (string): The pattern to match.
  • options (RegexOptions): The options to use when matching.

Returns:

  • MatchCollection: All matches of the pattern in the string with the specified options.

MatchValues(string regexPattern)

Returns all match values of the pattern in the string.

// Example usage with a string
string stringValue = "abc123def456";
IEnumerable<string> matchValues = stringValue.MatchValues("\\d+");
Console.WriteLine($"Match values: {string.Join(", ", matchValues)}");
// Output: Match values: 123, 456

Parameters:

  • value (string): The string to search.
  • regexPattern (string): The pattern to match.

Returns:

  • IEnumerable<string>: All match values of the pattern in the string.

MatchValues(string regexPattern, RegexOptions options)

Returns all match values of the pattern in the string with the specified options.

// Example usage with a string
string stringValue = "abc123def456";
IEnumerable<string> matchValues = stringValue.MatchValues("\\d+", RegexOptions.IgnoreCase);
Console.WriteLine($"Match values: {string.Join(", ", matchValues)}");
// Output: Match values: 123, 456

Parameters:

  • value (string): The string to search.
  • regexPattern (string): The pattern to match.
  • options (RegexOptions): The options to use when matching.

Returns:

  • IEnumerable<string>: All match values of the pattern in the string with the specified options.

Clone this wiki locally