C# 使用LINQ在两个字符串中比较字符序列

C# 使用LINQ在两个字符串中比较字符序列,c#,string,linq,C#,String,Linq,我有两条线可以说:- 字符串s1=“测试”; 字符串s2=“ASDTFGHEJKLSIOPT” 现在,如果我们仔细观察字符串s2中来自字符串s1的字符序列,我们会发现s2包含来自s1的所有字符,它们的序列相同,但索引不同 我想要一个解决方案(如果可能,使用LINQ或具有最小复杂度的数组解决方案),如果一个字符串包含另一个字符串中相同序列的所有字符,则返回true,而不考虑它们的索引,否则它应该返回false。您可以执行以下操作: string s1 = "TEST"; string s2 = "

我有两条线可以说:- 字符串s1=“测试”; 字符串s2=“ASDTFGHEJKLSIOPT”

现在,如果我们仔细观察字符串s2中来自字符串s1的字符序列,我们会发现s2包含来自s1的所有字符,它们的序列相同,但索引不同

我想要一个解决方案(如果可能,使用LINQ或具有最小复杂度的数组解决方案),如果一个字符串包含另一个字符串中相同序列的所有字符,则返回true,而不考虑它们的索引,否则它应该返回false。

您可以执行以下操作:

string s1 = "TEST"; string s2 = "ASDTFGHEJKLSIOPT";
//Will return all the matching characters without loosing their sequence
var matchingString = new string(s2.Where(r => s1.Contains(r)).ToArray());
if (matchingString.Contains(s1))
{
    //found
}
else
{
    //not found
}
这将确保匹配字符串是否包含相同序列中的
s1
,而与索引无关

Linq方法可用于此目的:

public static class TextHelper
{
    public static bool ContainsInterspersed(this string outer, string inner)
    {
        if (outer == null || inner == null)
            throw new ArgumentNullException();
        return ((IEnumerable<char>)inner).Aggregate(0, (nextIndex, ch) =>
            {
                nextIndex = (nextIndex < 0 ? nextIndex : outer.IndexOf(ch, nextIndex));
                if (nextIndex >= 0)
                    nextIndex++;
                return nextIndex;
            }) >= 0;
    }
}
公共静态类TextHelper
{
公共静态bool ContainsInterspersed(此字符串外部,字符串内部)
{
if(外部==null | |内部==null)
抛出新ArgumentNullException();
返回((IEnumerable)内部)。聚合(0,(nextIndex,ch)=>
{
nextIndex=(nextIndex<0?nextIndex:outer.IndexOf(ch,nextIndex));
如果(nextIndex>=0)
nextIndex++;
返回下一个索引;
}) >= 0;
}
}

这两个字符串的长度是线性的。此方法不会创建任何数组或子字符串。

我想要一个解决方案…
和一杯咖啡,而我们正在处理它?