I have the following code in java. What I am trying to search for is the word sql inside my a variable but I enter sql language and it says that the word has not been found. How can I do to search for sql even if I enter sql language of the 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);
}
}
The method
String#indexOf
will try to find the full text of what you indicate within the text string. Since your string has the value"sql"
and you're looking for"lenguaje sql"
, it won't find it since there's no trace of"lenguaje "
.What you're trying to do is kind of forced and maybe you shouldn't do it. On the other hand, maybe whatever you want to do is look to see if any of the "words" within your text string might be embedded in the string. To do this, you could use the following algorithm:
Per Mariano's comment, if we wanted to evaluate the string by removing not only whitespace but also any other character that is not a vowel or consonant, we use
\\W+
to separate the string:The method works the
indexOf
other way around.You must apply the method to the string in which you want to search, passing the text to search for as a parameter.
You can also use
contains
:All the other answers are the fastest 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 case .
Finding
"palabra"
within"ejemplo de ¿PaLaBrA?"
.Match the whole word .
And that it is NOT considered
"la"
as part of"dos palabras"
,but that it does coincide with
"(la primera)"
.For that, we'll use a regular expression , with wholeword bounds (
\b
) around the search word. That is, it is not preceded or followed by letters, numbers or an underscore.Example
Result
demo en ideone.com
This way you will be able to count how many times the second string appears within the first:
What you should do is something like the following.
If we wanted to evaluate the string by removing not only whitespace but also any other characters that are not vowels or consonants, we use \W+ to separate the string:
With the contentEquals function it is evaluated that the word is completely present, while in a contains it validates that at least one character of the requests to be searched is in the String. Greetings.