-2

I have this

String[] greet = "hi","hello","hey";
String match;
String sen = "hi, how are you?";
if(sen.contains(greet[]))
{
       //get the "hi" from the sen.
       Match = //the matching words           
}

I have to find a way of getting the word that the contain statement matched.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95

4 Answers4

3

Use linq's .Where to get the collection of words matching:

string[] greet = new string[] { "hi", "hello", "hey" };
string sen = "hi, how are you?";

List<string> matches = greet.Where(w => sen.Contains(w)).ToList();
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • It give me this "System.Collection.Generic.List'1[System.String] how should i fix this – JL Production Sep 30 '17 at 09:42
  • @JLProduction - you cannot use `ToString` on it - it is not a single string but a collection of strings. If you want to access for instance the first item in the collection you can do it with the indexer operator: `matches[0]` which will give you a single string – Gilad Green Sep 30 '17 at 10:49
  • @JLProduction - did you understand how to use this? – Gilad Green Oct 02 '17 at 05:33
0

Probably easier to use a foreach statement and loop through greet, and then split up sen by white space (ie. "") so you have two arrays. Then you can just check to see if your values match.

DjangoBlockchain
  • 534
  • 2
  • 17
0

You may want to split the sentence into words (let's decribe word as a nonempty sequence of letters or/and apostrophes - [\w']+):

  String sen = "hi, how are you?";

  // ["hi", "how", "are", "you"]
  String[] words = Regex
    .Matches(sen, @"[\w']+")
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

And then filter out all words that are in Greet:

  HashSet<string> greet = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { 
    "hi", "hello", "hey" };

  List<string> matches = words
    .Where(word => greet.Contains(word))
    .ToList();

Or if we combine both parts:

  HashSet<string> greet = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { 
    "hi", "hello", "hey" };

  List<string> matches = Regex
    .Matches(sen, @"[\w']+")
    .OfType<Match>()
    .Select(match => match.Value)
    .Where(word => greet.Contains(word))
    .ToList();

Please, nocice that HashSet<T> is often more convenient than T[] when we want to perform Contain.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
List<string> greet = new List<string>(){ "hi", "hello", "hey" };
List<string> matches;
string sentence = "hi, how are you?";
matches = greet.FindAll(g => sentence.Contains(g));
foreach (var match in matches)
    Console.WriteLine(match);
romerotg
  • 464
  • 2
  • 11