Quality Testing

Quality is delighting customers

How to print duplicate words in a sentence using Selenium WebDriver?

Print duplicate words in a sentence using Webdriver

Views: 239

Reply to This

Replies to This Discussion

Hi Madhavi,

You can use the below method to find the duplicate words in a sentence

Find the sentence using webdriver.findElement(By.xpath(locator))and use the below method by passing string as parameter.

/** * Method to find duplicate words in a Sentence or String */
public Set<String> duplicateWordsInSentence(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return Collections.emptySet();
Set<String> duplicates = new HashSet<String>();
String[] words = sentence.split("\\s+");
Set<String> set = new HashSet<String>();
for (String word : words) {
if (!set.add(word)) {

return duplicates;


Thanks Anand. It works fine.

Most software testing company asks these type of questions when hiring any new engineers to test their logical thinking.

So to get duplicate words from a sentence, first locate the sentence using the findElements & grab the text of the web element & put it into the String & then use the below-mentioned login in Java to bring the duplicate words.

package javaAutomation;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Count_Duplicate_words {

public static void main(String[] args) throws InterruptedException {

WebDriver driver;
System.setProperty("webdriver.chrome.driver", "c://selenium//chromedriver.exe");
driver = new ChromeDriver();
String string = driver
.findElement(By.xpath("//p[contains(text(),'If you want to create robust, browser-based regres')]"))

int count;

// Converts the string into lowercase
string = string.toLowerCase();

// Split the string into words using built-in function
String words[] = string.split(" ");

System.out.println("Duplicate words in a given string : ");
for (int i = 0; i < words.length; i++) {
count = 1;
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
// Set words[j] to 0 to avoid printing visited word
words[j] = "0";

// Displays the duplicate word if count is greater than 1
if (count > 1 && words[i] != "0")




Please do let me know if there's any doubt.




TTWT Magazine





© 2021   Created by Quality Testing.   Powered by

Badges  |  Report an Issue  |  Terms of Service