0

Let's say we'have code like that;

String s = "ali trees tree";
System.out.println(s.indexOf("tree"));

The output is 4. It's the beginning position of "trees". "Trees" word includes "tree" and I think because of that it gives wrong result.

Is it a way to find "tree" word's index with indexOf() function?

EkremC.
  • 61
  • 2

2 Answers2

0

You could use the following Regular Expression that checks if

  1. 'tree' is the last element of the string
  2. there's a whitespace after 'tree' (in case it's not in the end)

    /tree($|\s)/

If you are new to regular expressions please check this guide: http://www.tutorialspoint.com/java/java_regular_expressions.htm

Daniel Olivares
  • 544
  • 4
  • 13
0

I would also suggest that you can make an if statment checking the character after the last E in TREE, while first making sure another character actually exists in the string.

for example:

 boolean foundCorrectIndex=false;
 String tree = "tree";
 if (s.indexOf(tree) < s.length()-tree.length()){
int index = s.indexOf(tree)+tree.length();
if (s.charAt(index) == 's'){
foundCorrectIndex =true;
 }
}  

Hope that helps!

Ryan Cocuzzo
  • 3,109
  • 7
  • 35
  • 64