0

I'm writing a selenium webdriver java test and trying to count the number of names that appear without the last name following it.

For example, any time "John Smith" appears, it wouldn't be counted, but if it was a sentence like "John did this", since Smith didn't appear, it would increase the count.

Unfortunately at this point, trying to read/count from a WebElement is returning a 0 no matter what I do, but I know either way I wouldn't be excluding the last name entries. Any suggestions welcome!

Current code:

//get string from WebElement text
 `String john = JohnSmith.getText();
    int johnCount =0;
    while (john.contains("john")){
        johnCount++;

//this line starts from the substring after the first john
        john = john.substring(john.indexOf("john") + "john".length());
    }
MatthewC
  • 41
  • 7

1 Answers1

0

My first thought is to do something simple like replace "John Smith" with "" and then count the instances of "John". One simple way to count the instances is to split the string using "John" and count them.

A simple example:

String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
s = s.replaceAll("John Smith", "");
int count = s.split("John").length - 1;
System.out.println(count); // 2

EDIT: ... or better yet, turn it into a function that can be reused easily...

public int countFirstNames(String firstName, String lastName, String searchText)
{
    searchText = searchText.replace(firstName + " " + lastName, "");
    return searchText.split("John").length - 1;
}

and call it like

String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
System.out.println(countFirstNames("John", "Smith", s)); // 2
Community
  • 1
  • 1
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • Thanks for this. I had ended up with a far less efficient way of doing this. I used StringUtils.countMatches(THESTRING, "john"); and then subtracted StringUtils.countMatches(THE STRING, "john smith"); this was after calling tolower just in case any names weren't formatted properly. – MatthewC Oct 20 '16 at 17:52