In this tutorial you will learn about the Duplicate Words in String Program in Java and its application with practical example.
In this tutorial, we will learn to create a Duplicate Words in String Program in Java using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Duplicate Words in a String
Here we need to find out the duplicate words present in a string and display those words.
Example string = ” Hi, welcome to W3adda hi”
Output: “Hi”
Duplicate Words in String Program in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// java program to find duplicate word in a string.. public class Duplicate_string { public static void main(String args[]) { // Containing duplicate words in a string.. String str = "Duplicate => this is a example of duplicate string"; // Converting given Input String to lowerCase below: str= str.toLowerCase(); // Split the given Input String into words using fucntion split() method String[] wd = str.split(" "); // counting lenth of given string.. int length = wd.length; for( int i=0; i < length; i++) { // Set count to 1 for every iteration int count = 1; for(int j=i+1; j < length; j++) { if(wd[i].equals(wd[j])) { count++; // Set words[j]="0" to avoid Visited words counting wd[j] = "0"; } } if (wd[i] != "0" && count > 1) System.out.print(" "+wd[i]+" "); } } } |
Output
Duplicate Word
In the above program, we have first declared and initialized a set of variables required in the program.
- str= it will hold the string
- length= it will hold the length of a string
- i = for iteration
- wd = it will hold the duplicate words
After declaring variables we initiate values in str .
after initiating string in the variable str first of all we convert into lower case.
then we split a string into words by using the split() method.
then we count the length of a string
and within the loop we find duplicate word present in a string as shown mage below
And finally, we will print the duplicate values within the string.