How to print duplicate elements from given string in java. Write a java code to print duplicate elements from given string. complete java code for printing duplicate elemnts from given string.
Priniting duplicate elemnts in given string
what is duplicate element ?
Any element which is present more than once in given string is called as duplicate string. If the occurance of a particular character is greater than once in string we call it as duplicate element.
Example1: let the given string be “vrashikesh patil “
Duplicate elements (characters) in this string are : a,s,h,i. Note that we are not printing the repeated elemnts. Here a is repeating 2 times but we kust need to print it only once.
Example2: Let the given string be “Dattatrey patil”
Duplicate elements in this string are : a,t
Example3: Let the given string be “Hello world”
Duplicate elemnts in this strin are: l, o,
So from these examples we know what exactly is duplicate elemnt in string.
Java Code to find Duplicate Element
Algorithm:
- Take the input string from user
- Convert given string into string buffer.
- As it will be easy to do manuplations on string buffer.
- now with the help of two for loops iterate through elemnts of given string
- The outer for loop will be pointing the first element, second for loop will iterate through all other elements if there is any match between the current elemnt then increase the count by 1.
- So at the end of inner for loop if the count is greater than 1 then its a duplicate element so print it to output screen.
- Otherwise just got to second element.
- but in above step just to avoid printing the duplicate elemnts again and again make them as ‘o’ (as shown in below java code). This step will make sure that duplicate characters will not be printed.
- So at the end of outer for loop we will be getting all the duplicate elemntsfrom given string.
JAVA CODE for duplicate elements
package arrayPrograms; import java.util.*; class StringMethod { public String getDuplicate(String str) { char string[] = str.toCharArray(); int count; String string3=""; // getting duplicate elements from given string for(int i = 0; i <string.length; i++) { count = 1; for(int j = i+1; j <string.length; j++) { if(string[i] == string[j] && string[i] != ' ') { count++; string[j] = '0'; } } if(count > 1 && string[i] != '0') { string3=string3+string[i]; } } return string3; } public static void main(String[] args) { String string1="Doselect is a Great Platform"; StringMethod s1= new StringMethod(); System.out.println(s1.getDuplicate(string1)); } }
Watch complete explanation for above code here
Similar off campus coding questions
TCS Off Campus coding question solved
Reducing Dishes coding Complete solution
Pingback: Java Code to Find Unique characters from string - Is It Actually
Pingback: Important Difference between array list and linked list - Is It Actually
Thanks fօr ѕharing your thoughts on bagger. Regards