Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains all of the characters of a word

I wish to check if a string contains a all of the characters of a word given, for example:

var inputString = "this is just a simple text string";

And say I have the word:

var word = "ts";

Now it should pick out the words that contains t and s:

this just string

This is what I am working on:

var names = Regex.Matches(inputString, @"\S+ts\S+",RegexOptions.IgnoreCase);

however this does not give me back the words I like. If I had like just a character like t, it would give me back all of the words that contains t. If I had st instead of ts, it would give me back the word just.

Any idea of how this can work ?

like image 208
Nesquikk M Avatar asked Nov 22 '15 14:11

Nesquikk M


2 Answers

Here is a LINQ solution which is easy on the eyes more natural than regex.

var testString = "this is just a simple text string";
string[] words = testString.Split(' ');
var result = words.Where(w => "ts".All(w.Contains));

The result is:

this
just
string

like image 126
wingerse Avatar answered Oct 06 '22 18:10

wingerse


You can use LINQ's Enumerable.All :

var input = "this is just a simple text string";
var token = "ts";

var results  = input.Split().Where(str => token.All(c => str.Contains(c))).ToList();

foreach (var res in results)
    Console.WriteLine(res);

Output:

// this
// just
// string
like image 25
w.b Avatar answered Oct 06 '22 18:10

w.b