Table of Contents

StringExtensions Class

Definition

Namespace
Cuemon.Extensions
Assemblies
Cuemon.Extensions.Core.dll
Source
src/Cuemon.Extensions.Core/StringExtensions.cs

Extension methods for the string class.

public static class StringExtensions
Inheritance
StringExtensions

Examples

StringExtensions provides a comprehensive set of extension methods for string covering trimming, casing, content inspection, encoding, parsing, and utility operations. This example applies TrimAll to remove whitespace, ToCasing with LowerCase, UpperCase, and TitleCase modes, and content checks like IsEmailAddress, IsGuid, IsHex, IsNumeric, and IsBase64. It also demonstrates encoding conversions (ToByteArray, ToHexadecimal, FromBase64, FromUrlEncodedBase64), enum parsing ("Monday".ToEnum<DayOfWeek>()), delimited-string splitting (SplitDelimited with quoted fields), and utility operations such as Count, Difference, JsEscape, Chunk, PrefixWith, SuffixWith, and ToGuid. Console output confirms transformations like " Hello, World! " trimmed to "Hello,World!", "hello".SuffixWith(" world") producing "hello world", and "Monday".ToEnum<DayOfWeek>() returning DayOfWeek.Monday.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Cuemon;
using Cuemon.Extensions;
using Cuemon.Text;

namespace MyApp.Examples;

public class Example
{
    public void Run()
    {
        var value = " Hello, World! ";
        var answer = "yes";
        var chunkSource = "abcdefgh";
        var plainText = "Hello";
        var encodedText = "SGVsbG8=";
        var binarySource = "1101";
        var dayName = "Monday";
        var timeSource = "42";
        var counted = "hello";
        var quoted = "hello's";
        var guidSource = "550e8400-e29b-41d4-a716-446655440000";
        var uriSource = "https://example.com";
        var sequence = new[] { "1", "2", "3" };
        var emptySource = string.Empty;

        // Trim all whitespace characters
        var trimmed = value.TrimAll(); // "Hello,World!"

        // Convert to different casing styles
        var lower = value.ToCasing(CasingMethod.LowerCase); // " hello, world! "
        var upper = value.ToCasing(CasingMethod.UpperCase); // " HELLO, WORLD! "
        var title = value.ToCasing(CasingMethod.TitleCase, new CultureInfo("en-US")); // " Hello, World! "

        // Check string characteristics
        bool isEmail = value.IsEmailAddress(); // false
        bool isGuid = value.IsGuid(); // false
        bool isHex = value.IsHex(); // false
        bool isNumeric = value.IsNumeric(); // false
        bool isBase64 = value.IsBase64(); // false

        // Substring operations
        var before = value.SubstringBefore(","); // " Hello"
        var after = value.SuffixWithForwardingSlash(); // " Hello, World! /"
        var prefixed = value.PrefixWith(">>"); // ">> Hello, World! "

        // Remove and replace
        var removed = value.RemoveAll(" ", "!"); // "Hello,World"
        var replaced = value.ReplaceAll("world", "Earth"); // " Hello, Earth! "

        // Contains checks
        bool hasHello = value.ContainsAny("Hello", "World"); // true
        bool hasAll = value.ContainsAll("Hello", "World"); // true
        bool hasChar = value.ContainsAny('o', 'x'); // true

        // Equality checks
        bool equalsAny = answer.EqualsAny("yes", "no"); // true
        bool equalsAnyIgnoreCase = answer.EqualsAny(StringComparison.OrdinalIgnoreCase, "YES", "NO"); // true

        // StartsWith
        bool starts = value.StartsWith(" Hello"); // true

        // Chunk
        IEnumerable<string> chunks = chunkSource.Chunk(3); // ["abc", "def", "gh"]
        var chunksDefault = chunkSource.Chunk(); // ["abc", "def", "gh"]

        // Encoding conversions
        byte[] bytes = plainText.ToByteArray(o => o.Encoding = Encoding.UTF8);
        string hex = plainText.ToHexadecimal();
        string fromHex = hex.FromHexadecimal();

        // Base64
        byte[] base64Bytes = encodedText.FromBase64();
        var urlB64 = encodedText.FromUrlEncodedBase64(); // "Hello"

        // Enum parsing
        var day = dayName.ToEnum<DayOfWeek>(); // DayOfWeek.Monday

        // TimeSpan from string
        var ts = timeSource.ToTimeSpan(TimeUnit.Minutes); // 00:42:00

        // Delimited string splitting
        string csv = "apple,\"orange, citrus\",banana";
        string[] parts = csv.SplitDelimited(); // ["apple", "orange, citrus", "banana"]

        // Validate a sequence of strings against a target type
        bool isIntegerSequence = sequence.IsSequenceOf<int>(); // true

        // Additional string utilities
        int charCount = counted.Count('l'); // 2
        string diff = counted.Difference("world"); // "world"
        var biDigits = binarySource.FromBinaryDigits(); // new byte[] { 13 }
        bool emptyCheck = emptySource.IsNullOrEmpty(); // true
        bool emptySequenceCheck = sequence.IsNullOrEmpty(); // false
        var whitespaceSource = "   ";
        bool whiteSpaceCheck = whitespaceSource.IsNullOrWhiteSpace(); // true
        string jsEsc = quoted.JsEscape(); // "hello\\u0027s"
        string jsUnesc = quoted.JsUnescape(); // "hello's"
        string suffixed = counted.SuffixWith(" world"); // "hello world"
        Guid asGuid = guidSource.ToGuid();
        Uri asUri = uriSource.ToUri();
        Console.WriteLine(isIntegerSequence);
    }
}

Methods

Name Description
Chunk(string)

Returns a sequence that is chunked into string-slices having a length of 1024 that is equivalent to value.

Chunk(string, int)

Returns a sequence that is chunked into string-slices of the specified length that is equivalent to value. Default is 1024.

ContainsAll(string, StringComparison, params string[])

Returns a value indicating whether all of the specified values occurs within the value.

ContainsAll(string, params string[])

Returns a value indicating whether all of the specified values occurs within the value.

ContainsAny(string, char, StringComparison)

Returns a value indicating whether the specified find occurs within the value.

ContainsAny(string, params char[])

Returns a value indicating whether the specified values occurs within the value object.

ContainsAny(string, string, StringComparison)

Returns a value indicating whether the specified find occurs within the value.

ContainsAny(string, StringComparison, params char[])

Returns a value indicating whether the specified values occurs within the value object.

ContainsAny(string, StringComparison, params string[])

Returns a value indicating whether any of the specified values occurs within the value.

ContainsAny(string, params string[])

Returns a value indicating whether any of the specified values occurs within the value.

Count(string, char)

Counts the occurrences of character in the specified value.

Difference(string, string)

Returns the set difference between second and first or Empty if no difference.

EqualsAny(string, StringComparison, params string[])

Returns a value indicating the specified value equals one of the specified values.

EqualsAny(string, params string[])

Returns a value indicating the specified value equals one of the specified values.

FromBase64(string)

Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.

FromBinaryDigits(string)

Converts the specified input of binary digits to its equivalent byte array representation.

FromHexadecimal(string, Action<EncodingOptions>)

Converts the specified hexadecimal value to its equivalent string representation.

FromUrlEncodedBase64(string)

Converts the specified input of URL-safe base64 characters to its equivalent byte array representation.

IsBase64(string)

Determines whether the specified value matches a Base64 structure.

IsEmailAddress(string)

Determines whether the specified value has a valid format of an email address.

IsGuid(string, GuidFormats)

Determines whether the specified value has a valid format of a Guid.

IsHex(string)

Determines whether the specified value is hexadecimal.

IsNullOrEmpty(IEnumerable<string>)

Determines whether a string sequence has at least one value that equals to null or empty.

IsNullOrEmpty(string)

Determines whether the specified value is null or an Empty string.

IsNullOrWhiteSpace(string)

Determines whether the specified value is null, empty, or consists only of white-space characters.

IsNumeric(string, NumberStyles, IFormatProvider)

Determines whether the specified value can be evaluated as a number.

IsSequenceOf<T>(IEnumerable<string>, CultureInfo, ITypeDescriptorContext, Func<string, CultureInfo, bool>)

Determines whether the elements of the specified source is equivalent to the specified T.

JsEscape(string)

Escapes the given string the same way as the well known JavaScript escape() function.

JsUnescape(string)

Unescapes the given string the same way as the well known Javascript unescape() function.

PrefixWith(string, string)

Prefixes the source with the specified value.

RemoveAll(string, params char[])

Returns a new string in which all the specified filter values has been deleted from the specified value.

RemoveAll(string, StringComparison, params string[])

Returns a new string in which all the specified filter values has been deleted from the specified value.

RemoveAll(string, params string[])

Returns a new string in which all the specified filter values has been deleted from the specified value.

RemoveAll(string[], StringComparison, params string[])

Returns a new string array in which all the specified filter values has been deleted from the specified source array.

RemoveAll(string[], params string[])

Returns a new string array in which all the specified filter values has been deleted from the specified source array.

ReplaceAll(string, string, string, StringComparison)

Replaces all occurrences of oldValue in value, with newValue.

SplitDelimited(string, Action<DelimitedStringOptions>)

Returns a string array that contain the substrings of value delimited by a Delimiter that may be quoted by Qualifier.

StartsWith(string, IEnumerable<string>)

Determines whether the beginning of an instance of string matches at least one string in the specified sequence of strings.

StartsWith(string, StringComparison, IEnumerable<string>)

Determines whether the beginning of an instance of string matches at least one string in the specified sequence of strings.

StartsWith(string, StringComparison, params string[])

Determines whether the beginning of an instance of string matches at least one string in the specified sequence of strings.

StartsWith(string, params string[])

Determines whether the beginning of an instance of string matches at least one string in the specified sequence of strings.

SubstringBefore(string, string, StringComparison)

Retrieves a substring from the specified value. The substring starts at position 0 and continues until the first occurrence of match.

SuffixWith(string, string)

Suffixes the source with the specified value.

SuffixWithForwardingSlash(string)

Suffixes the source with a forwarding slash.

ToByteArray(string, Action<EncodingOptions>)

Converts the specified input to its equivalent byte array representation.

ToCasing(string, CasingMethod)

Converts the specified value to either lowercase, UPPERCASE, Title Case or unaltered.

ToCasing(string, CasingMethod, CultureInfo)

Converts the specified value to either lowercase, UPPERCASE, Title Case or unaltered using the specified culture.

ToEnum<TEnum>(string, bool)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated TEnum.

ToGuid(string, Action<GuidStringOptions>)

Converts the specified input of a GUID to its equivalent Guid structure.

ToHexadecimal(string, Action<EncodingOptions>)

Converts the specified value to its equivalent hexadecimal representation.

ToTimeSpan(string, TimeUnit)

Converts the specified value to its equivalent TimeSpan representation.

ToUri(string, UriKind)

Converts the specified value to its equivalent Uri representation.

TrimAll(string)

Removes all occurrences of white-space characters from the specified value.

TrimAll(string, params char[])

Removes all occurrences of a set of characters specified in trimChars from the specified value.