Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Check if string contains characters of another string at the same order

Tags:

string

c#

I would like to check if a string contains the characters of another string (returning true or false), but it needs to be in the "right" order but not necessarily contiguous.

Example:

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

String thirdWord = "road"; //FALSE - ARanDOmword

The word "arandomword" contains the letters of the word "road" but it's not possible to write it, because they are not at the right order.

Anyone, please?

like image 864
Anderson Gama Avatar asked Dec 08 '22 00:12

Anderson Gama


2 Answers

Use regex. Something simple that passes your tests in 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();
}
like image 76
Karl Avatar answered May 20 '23 11:05

Karl


you could define an extension method like this:

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;
    }
}

and call it as expressive as:

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
like image 29
nozzleman Avatar answered May 20 '23 09:05

nozzleman