Check if a word is within a sentence

Asked

Viewed 10,649 times

12

There is how I check if a word is within a phrase described by the user?

Ex:

palavra = "criativo";

Phrase written by the user:

"Eu sou criativo"

  • 1

    And if the phrase were Eu Sou Criativo? You would want to find the word Criativo with the C capital?

2 answers

21

You can use the method Contains().

    string frase = "Eu sou criativo";
    string palavra = "criativo";

    if(frase.Contains(palavra))
    {
        faça algo;
    }
  • 3

    True, String.Contains Method is the best way to know if the word is contained X in a given string.

  • To complement, Contains will call Indexof that will end up calling the implementation of CLR, so sometimes it is good to consider this.

6

In addition to using the Contains() to validate whether a string exists within another, you can also use StartsWith() to check whether a string begins with determined string, or the EndsWith() to check if it ends with determined string.

string frase = "eu sou criativo";

//Validar se contém "criativo"
if(frase.Contains("criativo")) { ... }

//Validar se começa com "criativo"
if(frase.StartsWith("criativo")) { ... }

//Validar se termina com "criativo"
if(frase.EndsWith("criativo")) { ... }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.