Fetch part of a string within a vector

Asked

Viewed 1,329 times

0

Well I have a vector that gets several lines of text. But I need to compare these lines and see if I can find a word, I tried it with equals() but it only returns true if it finds exactly the same string and contains() does not work with the vector. ex:

Word I want to seek: tomato

vector text:

[0] = Lettuces are green.

[1] = Os tomatos are red.

[2] = Peppers are coloured.

I left the code like this. It returns me the line in which is the word searched which already serves for my goals.

public int buscaLinha(String[] vetor, String palavra)
{
   int i = 1;
   for(String p : vetor)
   {
       if(p.contains(palavra)) {
           return i;
       }
       i++;
   }

   return 0;
}

I would like to thank you in advance for your attention to me.

3 answers

3


You can try with the following code:

public boolean encontrarPalavra(String[] vetor, String palavra)
{
   for(String p : vetor)
   {
       if(p.contains(palavra))
         return true;
   }

   return false;
}
  • Thanks for helping!

0

Example code in PHP

public function buscarPalavra ($palavraBuscada, $array)
{
   if(in_array($palavraBuscada,$array)){
      echo "Palavra encontrada: $palavraBuscada";
   }else{
      echo "Palavra Não Localizada!";
   }
}
  • 3

    Olá Christian, welcome to Stackoverflow in English. I believe he wants the answer in Java, because this was used tag in the question.

  • Vlw guy in php I already knew, but thanks for sharing.

0

I don’t know if JAVA contains the Substring method, but if it does, it might be an option. I developed this in C# and it worked, as C# is relatively similar to JAVA, I put this method here to try to help as well. This method is similar to that put by Murilo Fechio:

public static bool existe_no_vetor (string[] aux, string strpretendida)
{
    foreach (string str in aux)
        {
            if (str.Contains(strpretendida) == true)
                return true;
        }

    return false;
}

Good luck!

  • Thanks for the help, I’ll probably use it when I go back to programming in C#

Browser other questions tagged

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