Word By Word Comparison
I want to ask if anyone knows whether Java has built in library for doing something like the following.
For instance,
I have 2 Strings which are: String a = "Yeahh, I love Java programming."; String b = "love";
I want to check whether the String b which contains "love" is part of the tokens in the String a. Hence, I want to ask are there any Java API to do so? I want something like,
a.contains (b) <--------- Return true result
Are there any??? because,,,,if there's no Jav开发者_JAVA百科a API for that, I would write my own algorithm then.
Thanks in advance for any helps..^^
The suggestions so far (indexOf
, contains
) are all fine if you just want to find substrings. However, given the title of your question, I assume you actually want to find words. For instance, if asked whether "She wore black gloves" contained "love" my guess is you'd want the answer to be no.
Regular expressions are probably the best way forward here, using a word boundary around the word in question:
import java.util.regex.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(containsWord("I love Java", "love"));
System.out.println(containsWord("She wore gloves", "love"));
System.out.println(containsWord("start match", "start"));
System.out.println(containsWord("match at end", "end"));
}
public static boolean containsWord(String input, String word)
{
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
return pattern.matcher(input).find();
}
}
Output:
true
false
true
true
string strToCheck = "check me";
int firstOccurence = strToCheck .indexOf("me");
//0 if no any
the method contains(CharSequence s) exist in the class String.
So your a.contains(b) will work
You can use the indexOf() function in the String library to check for it:
if(a.indexOf(b)>=0)
return true;
Yes, there is: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence).
If you want to find the words will be quite easy, you just have to use split.
//Split to an array using space as delimiter
String[] arrayOfWords = a.split(" ");
And then you'll compare like:
"love".equalsIgnoreCase(arrayOfWords[i]);
something like that, you get the idea
精彩评论