Mohit S
Mohit S

Reputation: 14064

Sequential Combination of string from string

I am stumped. I wanted to know if any combination in sequence order of the string is available. like for example my string to match is

string somevar = "rat";

then if an another string contains "rat", "at", "ra" or "r", "a", "t" it should return false.

I can only think of making condition for every single sequence i can manually find. but I am sure there could be some trick to find it easily. I had a look on Implement a function that prints all possible combinations of the characters in a string but it doesnt do what I want.

I am sorry if this is not very clear but I want to check a condition where

 if(somevar == "rat" || somevar == "at" || somevar == "ra" || somevar == "r" || somevar == "a" || somevar == "t")
 {
      \\do something
 }

Upvotes: 0

Views: 289

Answers (3)

fubo
fubo

Reputation: 46005

You need a method that determines all substrings

public static IEnumerable<string> GetAllSubStrings(string input, int length)
{
    for (var i = 0; i < input.Length - length + 1; i++)
    {
        yield return input.Substring(i, length);
    }
}

then you can just create a list with all combintaions

string somevar = "rat";
List<string> subStrings = new List<string>();
for (int i = 0; i < somevar.Length; i++)
{
    subStrings.AddRange(GetAllSubStrings(somevar, i + 1));
}
// subStrings = {"rat", "at", "ra", "r", "a", "t"}

and finally check your other string against that list.

UPDATE to your updated Question:

//check "ra" 
string testItem = "ra";
bool contains = subStrings.Any(x => testItem == x);

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460360

You don't need to check all substrings if it's sufficient that a single char is contained:

bool containsAnyChar = somevar.Intersect("rat").Any();

That works because a string implements IEnumerable<char>(is a collection of characters).

Upvotes: 4

Manoj
Manoj

Reputation: 59

string somevar = "rat";
string anotherString = "rat is there";
bool result = somevar.ToCharArray().Any(ch => anotherString.Contains(ch));

Upvotes: -1

Related Questions