IndexOf () search for a word in a phrase

23

I have the following code in java. What I try to look for is the word sql inside my variable a but I enter sql language and it turns out that the word has not been found. How can I do to find sql even if I enter sql language of variable a? I hope you can help me thanks

public static void main(String[] args) {
            // TODO code application logic here
            String a="sql";
            int intIndex = a.indexOf("lenguaje sql");
          if(intIndex == - 1){
             System.out.println("palabra encontrada");
          }else{
             System.out.println("palabra no encontrada"
             + intIndex);
          }

        }
    
asked by Dimoreno 11.05.2016 в 23:17
source

6 answers

9

The String#indexOf method will try to find the full text of what you indicate within the text string. Since your text string has the value "sql" and you are looking for "lenguaje sql" , you will not find it since there is no trace of "lenguaje " .

What you are trying to do is a forced one and maybe you should not do it. On the other hand, it may be that whatever you want to do is search if any of the "words" within your text string can be embedded in the string. For this, you could use the following algorithm:

String cadenaDondeBuscar = "sql";
String loQueQuieroBuscar = "lenguaje sql";
String[] palabras = loQueQuieroBuscar.split("\s+");
for (String palabra : palabras) {
    if (cadenaDondeBuscar.contains(palabra)) {
        System.out.println("Encontrado");
        //aquí tu lógica en caso que se haya encontrado...
    }
}

For Mariano's comment, if you want to evaluate the string by removing not only the blank spaces but also any other character that is not a vowel or consonant, we use \W+ to separate the string:

String cadenaDondeBuscar = "sql";
String loQueQuieroBuscar = "lenguaje sql";
String[] palabras = loQueQuieroBuscar.split("\W+");
for (String palabra : palabras) {
    if (cadenaDondeBuscar.contains(palabra)) {
        System.out.println("Encontrado");
        //aquí tu lógica en caso que se haya encontrado...
    }
}
    
answered by 11.05.2016 / 23:27
source
10

The operation of the method indexOf is the other way around.

You must apply the method to the string in which you want to search, passing it as a parameter the text to search.

String a = "sql";
String texto = "lenguaje sql";
int intIndex = texto.indexOf(a);
    
answered by 11.05.2016 в 23:32
8

You can also use contains :

String palabra = "sql";
String texto = "lenguaje sql";
boolean resultado = texto.contains(palabra);

if(resultado){
    System.out.println("palabra encontrada");
}else{
    System.out.println("palabra no encontrada");
}
    
answered by 11.05.2016 в 23:55
5

All other answers are the quickest way to see if one string is part of another. However, when searching for words , you may want to meet the following conditions:

  • Match ignoring uppercase and lowercase .
    Finding "palabra" within "ejemplo de ¿PaLaBrA?" .

  • Coincide with the whole word .
    And that is NOT considered "la" as part of "dos palabras" ,
    but that does match "(la primera)" .

For that, we will use a regular expression , with Full word limits ( \b ) around the searched word. That is, it is not preceded or succeeded by letters, numbers or a low script.

Example

import java.util.regex.*;
String aguja = "sql";             //palabra buscada
String pajar = "lenguaje SQL";    //texto

//escapar y agregar limites de palabra completa - case-insensitive
Pattern regex = Pattern.compile("\b" + Pattern.quote(aguja) + "\b", Pattern.CASE_INSENSITIVE);
Matcher match = regex.matcher(pajar);

//la palabra está en el texto??
if (match.find()) {  //si se quiere encontrar todas las ocurrencias: cambiar el if por while
    System.out.println("Encontrado: '" + match.group() 
                     + "' dentro de '" + pajar 
                     + "' en la posición " + match.start());
} else {
    System.out.println("'" + aguja + "' NO está dentro de '" + pajar);
}

Result

Encontrado: 'SQL' dentro de 'lenguaje SQL' en la posición 9

demo on ideone.com

    
answered by 29.07.2016 в 05:20
1

This way you will be able to count how many times the second chain appears within the first one:

    String cadena1 = in.nextLine();
    cadena1 = cadena1.toLowerCase();
    String cadena2 = in.nextLine();
    cadena2 = cadena2.toLowerCase();
    System.out.println(" ");

    int contador = 0;

    while (cadena1.indexOf(cadena2) > -1) {
        cadena1 = cadena1.substring(cadena1.indexOf(cadena2) + cadena2.length(), cadena1.length());
        contador++;
    }

    System.out.println("La segunda cadena se incluye " + contador + " veces en la primera cadena.");
    
answered by 12.11.2018 в 19:46
0

What you should do is something like the following.

public static void main(String[] args) {
            // TODO code application logic here
            String a="lenguaje sql";
            int intIndex = a.indexOf("sql");
          if(intIndex == - 1){
             System.out.println("palabra no encontrada");
          }else{
             System.out.println("palabra encontrada a partir del carácter en la posicion: "
             + intIndex);
          }

        }
    
answered by 11.10.2017 в 20:36