I am writing a piece of code in which i have to find only complete words for example if i have
String str = \"today is tuesday\";
and I\'m
String str = "today is tuesday";
StringTokenizer stringTokenizer = new StringTokenizer(str);
bool exists = false;
while (stringTokenizer.hasMoreTokens()) {
if (stringTokenizer.nextToken().equals("t")) {
exists = true;
break;
}
}
I use a regexps for such tasks. In your case it should look something like this:
String str = "today is tuesday";
return str.matches(".*?\\bt\\b.*?"); // returns "false"
String str = "today is t uesday";
return str.matches(".*?\\bt\\b.*?"); // returns "true"
A short explanation:
. matches any character, *? is for zero or more times, \b is a word boundary.
More information on regexps can be found here or specifically for java here
use a regex like "\bt\b".
I would recommend you use the "split" functionality for String with spaces as separators, then go through these elements one by one and make a direct comparison.
I would suggest using this regex pattern1 = ".\bt\b." instead of pattern2 = ".?\bt\b.?" . Pattern1 will help you to match the complete String if 't' occurs in that string rather than the pattern2 which just reaches the string "t" you are searching for and ignores rest of the string. There is not much difference in two approaches and for your particular use case of returning true/false will run fine both the ways. The one I suggested will help you to improvise the regex in case you make further changes in your use case
you can do that by putting a regex which should end with a space.