ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Difference

Calculates the difference between two strings, returning the remainder of the second string starting from where it differs from the first.

Source

public static string Difference(this string ? value, string str, bool ignoreCase) {
    if (value == null)
        return str;

    if (str == null)
        return value;

    string valueLower = value;
    string strLower = str;

    if (ignoreCase) {
        valueLower = valueLower.ToLowerInvariant();
        strLower = strLower.ToLowerInvariant();
    }

    // Find the common prefix length
    int prefixLength = 0;
    for (int i = 0; i < Math.Min(value.Length, str.Length); i++) {
        if (valueLower[i] != strLower[i]) {
            break;
        }

        prefixLength++;
    }

    // Return the remainder of the second string starting from the different part
    return str[prefixLength..];
}

Example

string str1 = "hello world";
string str2 = "hello sunshine";
string difference = str1.Difference(str2, false); // Case-sensitive: difference will be " sunshine"

str1 = "MyFile.txt";
str2 = "MyFile.pdf";
difference = str1.Difference(str2, false); // Case-sensitive: difference will be ".pdf"

Author: Kalkwst

Submitted on: 29 feb. 2024

Language: csharp

Type: System.String

Views: 786