C# - 检查字符串是否包含相同顺序的另一个字符串的字符

And*_*ama 3 c# string

我想检查一个字符串是否包含另一个字符串的字符(返回true或false),但它需要处于"正确"的顺序,但不一定是连续的.

例:

String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword

String thirdWord = "road"; //FALSE - ARanDOmword
Run Code Online (Sandbox Code Playgroud)

单词"arandomword"包含单词"road"的字母,但不可能写出来,因为它们的顺序不正确.

有人吗?

Kar*_*arl 5

使用正则表达式.在linqpad中通过测试的简单方法:

void Main()
{
    String firstWord = "arm";
    String secondWord = "arandomword"; //TRUE - ARandoMword

    String thirdWord = "road";

    Regex.IsMatch(secondWord,makeRegex(firstWord.ToCharArray())).Dump();
}

// Define other methods and classes here
String makeRegex(char[] chars)
{
    StringBuilder sb = new StringBuilder();
    foreach (var element in chars.Select(c => Regex.Escape(c.ToString()))
        .Select(c => c + ".*"))
    {
        sb.Append(element);
    }
    return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)


noz*_*man 5

你可以像这样定义一个扩展方法:

public static class StringExtensions
{
    public static bool ContainsWord(this string word, string otherword)
    {
        int currentIndex = 0;

        foreach(var character in otherword)
        {
            if ((currentIndex = word.IndexOf(character, currentIndex)) == -1)
                return false;
        }

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其称为富有表现力的:

String firstWord = "arm";
String secondWord = "arandomword"; //TRUE - ARandoMword
String thirdWord = "road"; //FALSE - ARanDOmword

var ret = secondWord.ContainsWord(firstWord); // true
var ret2 = thirdWord.ContainsWord(firstWord); // false
Run Code Online (Sandbox Code Playgroud)