String Extensions - SaintOswald/SaintOswald.Libraries.Extensions GitHub Wiki

Home > String Extensions

Requirements

Make the StringExtensions library available for use:

using SaintOswald.Libraries.Extensions.StringExtensions;

Extensions


CollapseWhiteSpace(str)

Collapses white space in the specified string by replacing all non-space white space characters with a space (i.e. " "). Replaces consecutive spaces with a single space and trims leading and trailing spaces

Name Description
str System.String
The string to collapse white space for

Returns

The specified string with white space collapsed

Sample Usage

[TestMethod]
public void TestCollapseWhiteSpace()
{
    Assert.AreEqual("Test Collapse White Space", "Test\tCollapse\r\nWhite Space".CollapseWhiteSpace());
}

EverythingAfterFirst(str, delimiter, comparisonType)

Returns everything after the first occurrence of the specified delimiter

Name Description
str System.String
The string to return everything after the first occurrence of the delimiter for
delimiter System.String
The delimiter to return everything after
comparisonType System.StringComparison
The String Comparison Type to use (optional - defaults to StringComparison.Ordinal)

Returns

Returns everything after the first occurrence of the specified delimiter if it exists within the given string, otherwise returns null

Exceptions

System.ArgumentException: Thrown when the specified delimiter is null or empty

Sample Usage

[TestMethod]
public void TestEverythingAfterFirst()
{
    Assert.AreEqual("example.com", "[email protected]".EverythingAfterFirst("@"));
}
[TestMethod]
public void TestEverythingAfterFirstSpecifyStringComparison()
{
    Assert.IsNull("[email protected]".EverythingAfterFirst("@E"));
    Assert.AreEqual("xample.com", "[email protected]".EverythingAfterFirst("@E", StringComparison.CurrentCultureIgnoreCase));
}

EverythingAfterLast(str, delimiter, comparisonType)

Returns everything after the last occurrence of the specified delimiter

Name Description
str System.String
The string to return everything after the last occurrence of the delimiter for
delimiter System.String
The delimiter to return everything after
comparisonType System.StringComparison
The String Comparison Type to use (optional - defaults to StringComparison.Ordinal)

Returns

Returns everything after the last occurrence of the specified delimiter if it exists within the given string, otherwise returns null

Exceptions

System.ArgumentException: Thrown when the specified delimiter is null or empty

Sample Usage

[TestMethod]
public void TestEverythingAfterLast()
{
    Assert.AreEqual("example.com", "[email protected]".EverythingAfterLast("@"));
}
[TestMethod]
public void TestEverythingAfterLastSpecifyStringComparison()
{
    Assert.IsNull("[email protected]".EverythingAfterLast("@E"));
    Assert.AreEqual("xample.com", "[email protected]".EverythingAfterLast("@E", StringComparison.CurrentCultureIgnoreCase));
}

EverythingBeforeFirst(str, delimiter, comparisonType)

Returns everything before the first occurrence of the specified delimiter

Name Description
str System.String
The string to return everything before the first occurrence of the specified delimiter for
delimiter System.String
The delimiter to return everything before
comparisonType System.StringComparison
The String Comparison Type to use (optional - defaults to StringComparison.Ordinal)

Returns

Returns everything before the first occurrence of the specified delimiter if it exists within the given string, otherwise returns null

Exceptions

System.ArgumentException: Thrown when the specified delimiter is null or empty

Sample Usage

[TestMethod]
public void TestEverythingBeforeFirst()
{
    Assert.AreEqual("test", "[email protected]".EverythingBeforeFirst("@"));
}
[TestMethod]
public void TestEverythingBeforeFirstSpecifyStringComparison()
{
    Assert.IsNull("[email protected]".EverythingBeforeFirst("@E"));
    Assert.AreEqual("test", "[email protected]".EverythingBeforeFirst("@E", StringComparison.CurrentCultureIgnoreCase));
}

EverythingBeforeLast(str, delimiter, comparisonType)

Returns everything before the last occurrence of the specified delimiter

Name Description
str System.String
The string to return everything before the last occurrence of the specified delimiter for
delimiter System.String
The delimiter to return everything before
comparisonType System.StringComparison
The String Comparison Type to use (optional - defaults to StringComparison.Ordinal)

Returns

Returns everything before the last occurrence of the specified delimiter if it exists within the given string, otherwise returns null

Exceptions

System.ArgumentException: Thrown when the specified delimiter is null or empty

Sample Usage

[TestMethod]
public void TestEverythingBeforeLast()
{
    Assert.AreEqual("test", "[email protected]".EverythingBeforeLast("@"));
}
[TestMethod]
public void TestEverythingBeforeLastSpecifyStringComparison()
{
    Assert.IsNull("[email protected]".EverythingBeforeLast("E"));
    Assert.AreEqual("test@exampl", "[email protected]".EverythingBeforeLast("E", StringComparison.CurrentCultureIgnoreCase));
}

IsNullOrEmpty(str)

Checks if the specified string is null or empty

Name Description
str System.String
The string to check

Returns

True if the specified string is null or empty, otherwise returns false

Sample Usage

[TestMethod]
public void TestIsNullOrEmpty()
{
    string s = null;
    Assert.IsTrue(s.IsNullOrEmpty());
    Assert.IsTrue("".IsNullOrEmpty());

    Assert.IsFalse("Test of IsNullOrEmpty".IsNullOrEmpty());
}

IsNullOrWhiteSpace(str)

Checks if the specified string is null or white space

Name Description
str System.String
The string to check

Returns

True if the specified string is null or whitespace, otherwise returns false

Sample Usage

[TestMethod]
public void TestIsNullOrWhiteSpace()
{
    string s = null;
    Assert.IsTrue(s.IsNullOrWhiteSpace());
    Assert.IsTrue("".IsNullOrWhiteSpace());
    Assert.IsTrue(" ".IsNullOrWhiteSpace());
    Assert.IsTrue(Environment.NewLine.IsNullOrWhiteSpace());

    Assert.IsFalse("Test of IsNullOrWhitespace".IsNullOrWhiteSpace());
}

RemoveDiacritics(str)

Attempts to remove diacritics from the specified string. For example, an accented French character like "á" should be replaced with "a"

Name Description
str System.String
The string to attempt to remove diacritics from

Returns

The string with diacritics removed

Sample Usage

[TestMethod]
public void TestRemoveDiacritics()
{
    Assert.AreEqual("acdeeinorstuuyz", "ácdéeínórštúuýž".RemoveDiacritics());  // Czech
    Assert.AreEqual("aaeeeeiiouuuy", "àâéèêëïîôùûüÿ".RemoveDiacritics());      // French
    Assert.AreEqual("aou", "äöü".RemoveDiacritics());                          // German
    Assert.AreEqual("aenzz", "aenzz".RemoveDiacritics());                      // Polish
    Assert.AreEqual("aaaaceeiooouu", "ãáàâçéêíõóôúü".RemoveDiacritics());      // Portuguese
    Assert.AreEqual("aaeo", "äåéö".RemoveDiacritics());                        // Swedish
}

Repeat(str, repetitions)

Returns the specified string value repeated for the given number of repetitions

Name Description
str System.String
The string value to repeat
repetitions System.Int32
The number of repetitions to repeat the string for - must be at least 2

Returns

The specified string repeated for the given number of repetitions

Exceptions

System.ArgumentException: Thrown when the specified repetitions is less than 2

Sample Usage

[TestMethod]
public void TestRepeat()
{
    Assert.AreEqual("-----", "-".Repeat(5));
}

Replace(str, regex, replacement)

Replaces all values matched by the specified regular expression with the given replacement

Name Description
str System.String
The string to replace matched values for
regex System.Text.RegularExpressions.Regex
The regular expression to match the specified string against
replacement System.String
The string to replace values matched by the specified regular expression with

Returns

The specified string with values matched by the given regular expression replaced with the replacement value

Exceptions

System.ArgumentNullException: Thrown when the specified replacement is null

Sample Usage

[TestMethod]
public void TestReplace()
{
    Assert.AreEqual("123TestABC", "123Test123".Replace(new Regex(@"\d{3}$"), "ABC"));
}

ToPluralForCount(str, count, pluralForm)

Returns the plural form of the specified string when the given count is less than or equal to 0 or greater than 1. The plural form is obtained by adding "s" to the specified string or by returning the given plural form when specified. If the specified count is 1 the original string value is returned

Name Description
str System.String
The string to return the plural form for
count System.Int32
The count to determine if the plural or singular form of the specified string should be returned
pluralForm System.String
The plural form to return for the given string (optional)

Returns

Returns either the specified string plus "s" or the optional specified plural form if the given count is less than or equal to 0 or greater than 1. If the count is 1 then the original string value is returned

Exceptions

System.ArgumentException: Thrown when plural form has been specified but is empty or white space

Sample Usage

[TestMethod]
public void TestToPluralForCount()
{
    Assert.AreEqual("Test", "Test".ToPluralForCount(1));   // There is 1 Test
    Assert.AreEqual("Tests", "Test".ToPluralForCount(0));  // There are 0 Tests
    Assert.AreEqual("Tests", "Test".ToPluralForCount(2));  // There are 2 Tests
}
[TestMethod]
public void TestToPluralForCountSpecifyPluralForm()
{
    Assert.AreEqual("Category", "Category".ToPluralForCount(1, "Categories"));    // There is 1 Category
    Assert.AreEqual("Categories", "Category".ToPluralForCount(0, "Categories"));  // There are 0 Categories
    Assert.AreEqual("Categories", "Category".ToPluralForCount(2, "Categories"));  // There are 2 Categories
}

ToSlug(str)

Converts the specified string to a slug by removing diacritics, converting to lowercase, collapsing white space, replacing spaces with hyphens (-), stripping characters that are not alpha-numeric or hyphens, removing consecutive hyphens and trimming leading and trailing hyphens and spaces

Name Description
str System.String
The string to convert to a slug

Returns

The string converted to a slug

Exceptions

System.ArgumentException: Thrown when the specified string is null, empty or white space

Sample Usage

[TestMethod]
public void TestToSlug()
{
    Assert.AreEqual("test-to-slug", "Test to Slug".ToSlug());
}

ToTitleCase(str, cultureInfo)

Converts the specified string to title case by capitalising the first letter of each word using the culture of the current thread. Words entirely in uppercase are treated as acronyms and not modified

Name Description
str System.String
The string to convert to title case
cultureInfo System.Globalization.CultureInfo
The culture info to use when converting the string to title case (optional - defaults to CultureInfo.CurrentCulture)

Returns

The specified string converted to title case

Sample Usage

[TestMethod]
public void TestToTitleCase()
{
    Assert.AreEqual("Test Of To Title Case", "test of to title case".ToTitleCase());
}
[TestMethod]
public void TestToTitleCaseSpecifyCulture()
{
    Assert.AreEqual("İngilis Dili Danismaq Edirsiniz?", "ingilis dili danismaq edirsiniz?".ToTitleCase(new CultureInfo("az-Latn-AZ")));  // Azerbaijani
}

ToUpperFirst(str, cultureInfo)

Converts the first letter of the specified string to uppercase

Name Description
str System.String
The string to convert the first letter to upper case for
cultureInfo System.Globalization.CultureInfo
The culture info to use when converting the first letter to uppercase (optional - defaults to CultureInfo.CurrentCulture)

Returns

The specified string with the first letter converted to uppercase

Sample Usage

[TestMethod]
public void TestToUpperFirst()
{
    Assert.AreEqual("Test", "test".ToUpperFirst());
}
[TestMethod]
public void TestToUpperSpecifyCulture()
{
    Assert.AreEqual("İngilis", "ingilis".ToUpperFirst(new CultureInfo("az-Latn-AZ")));  // Azerbaijani
}

TrimEndWhiteSpaceAndPunctuation(str)

Trims trailing white space and punctuation characters from the specified string

Name Description
str System.String
The string to trim

Returns

The specified string with trailing white space and punctuation characters removed

Sample Usage

[TestMethod]
public void TestTrimEndWhiteSpaceAndPunctuation()
{
    Assert.AreEqual("Test of trim end white space and punctuation", "Test of trim end white space and punctuation ".TrimEndWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", $"Test of trim end white space and punctuation{Environment.NewLine}".TrimEndWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", "Test of trim end white space and punctuation?".TrimEndWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", "Test of trim end white space and punctuation? ! @ ".TrimEndWhiteSpaceAndPunctuation());
}

TrimStartWhiteSpaceAndPunctuation(str)

Trims leading white space and punctuation characters from the specified string

Name Description
str System.String
The string to trim

Returns

The specified string with leading white space and punctuation characters removed

Sample Usage

[TestMethod]
public void TestTrimStartWhiteSpaceAndPunctuation()
{
    Assert.AreEqual("Test of trim end white space and punctuation", " Test of trim end white space and punctuation".TrimStartWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", $"{Environment.NewLine}Test of trim end white space and punctuation".TrimStartWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", "?Test of trim end white space and punctuation".TrimStartWhiteSpaceAndPunctuation());
    Assert.AreEqual("Test of trim end white space and punctuation", "? ! @ Test of trim end white space and punctuation".TrimStartWhiteSpaceAndPunctuation());
}

Truncate(str, maximumLength)

Truncates the specified string to the given maximum length. The string will be returned as-is if it's length is shorter than or equal to the maximum length. A truncated string will be suffixed with "..." and the truncated string plus the suffix will be no longer than the maximum length. Trailing punctuation and white space will be removed from truncated strings

Name Description
str System.String
The string to truncate
maximumLength System.Int32
The maximum length of the truncated string - must be at least 3

Returns

The truncated string

Exceptions

System.ArgumentException: Thrown when the specified maximum length is less than 3

Sample Usage

[TestMethod]
public void TestTruncate()
{
    Assert.AreEqual("Test of trun...", "Test of truncation".Truncate(15));
}
[TestMethod]
public void TestTruncateStripsTrailingPunctuation()
{
    Assert.AreEqual("Test of...", "Test of??????????truncation".Truncate(12));
}

TryParseTo<T>(str)

Attempts to parse the specified string value to the given type

Name Description
str System.String
The string value to attempt to parse to the specified type

Returns

The string value parsed to the specified type

Exceptions

System.ArgumentException: Thrown when the specified string value cannot be parsed to the given type

Sample Usage

[TestMethod]
public void TestTryParseTo()
{
    Assert.AreEqual<int>(1, "1".TryParseTo<int>());
    Assert.AreEqual<uint>(1, "1".TryParseTo<uint>());
    Assert.AreEqual<Int16>(1, "1".TryParseTo<Int16>());
    Assert.AreEqual<UInt16>(1, "1".TryParseTo<UInt16>());
    Assert.AreEqual<Int32>(1, "1".TryParseTo<Int32>());
    Assert.AreEqual<UInt32>(1, "1".TryParseTo<UInt32>());
    Assert.AreEqual<Int64>(1, "1".TryParseTo<Int64>());
    Assert.AreEqual<UInt64>(1, "1".TryParseTo<UInt64>());
    Assert.AreEqual<short>(1, "1".TryParseTo<short>());
    Assert.AreEqual<ushort>(1, "1".TryParseTo<ushort>());
    Assert.AreEqual<long>(1, "1".TryParseTo<long>());
    Assert.AreEqual<ulong>(1, "1".TryParseTo<ulong>());

    Assert.AreEqual<float>(1.1f, "1.1".TryParseTo<float>());
    Assert.AreEqual<double>(1.1, "1.1".TryParseTo<double>());
    Assert.AreEqual<decimal>(1.1M, "1.1".TryParseTo<decimal>());
}

ValueOr(str, alternative)

Returns the string value or the specified alternative if the string value is null, empty or white space

Name Description
str System.String
The string to return either the value or the alternative for
alternative System.String
The alternative value to return if the string value is null, empty or white space

Returns

The string value or the specified alternative if the string value is null, empty or white space

Sample Usage

[TestMethod]
public void TestValueOr()
{
    Assert.AreEqual("Test", "Test".ValueOr("Alternative"));
}
[TestMethod]
public void TestValueOrReturnsAlternativeWhenNull()
{
    string s = null;
    Assert.AreEqual("Alternative", s.ValueOr("Alternative"));
}
[TestMethod]
public void TestValueOrReturnsAlternativeWhenEmpty()
{
    Assert.AreEqual("Alternative", "".ValueOr("Alternative"));
}
[TestMethod]
public void TestValueOrReturnsAlternativeWhenWhiteSpace()
{
    Assert.AreEqual("Alternative", "   ".ValueOr("Alternative"));
}

⚠️ **GitHub.com Fallback** ⚠️