[Solved] FLUTTER - Checking if a string contains another one

Question

Asked by SylvainJack on January 13, 2022 (source).

I am working on an English vocabulary learning app. Some of the exercises given to the users are written quizzes. They have to translate French words into English words and vice versa.

To make the checking a little more sophisticated than just "1" or "0" (TypedWord == expectedWord), I have been working with similarities between strings and that worked well (for spelling mistakes for example).

I had also used the contains function, so that for example, if the user adds an article in front of the expected word, it doesn't consider it wrong. (Ex : Ecole (School is expected), but user writes "A school").

So I was checking with lines such as "if (typedWord.contains(word)==true) then...". It works fine for the article problem. But it prompts another issue :

Ex : A bough --> the expected French word is "branche". If user types "une branche", it considers it correct, which is great. But if user types "débrancher" (to unplug), it considers it correct as well as the word "branche" is a part of "débrancher"...

How could I keep this from happening ? Any idea of other ways to go about it ?

I read the three proposed answers which are really interesting. The thing is that some of the words are compound.... "Ex : kitchen appliance, garden tool" etc... so then I think the "space" functions might be problematic...

Answer

Question answered by Gourango S (source).

In this case, separate the whole answer with the "space", then compare it with the correct word.

For an example:
User's answer: That is my school
Separate it with space, so that you will find an array of words:
that, is, my, school. 

Then compare each word with your word. It will give you the correct answer.

The flutter code will be like below:

  usersAnswer?.split(" ").forEach((word){
    if(word == correctAnswer) 
      print("this is a correct answer");
  });
CONTAINS DART FLUTTER LIST
SHARE: