Hello coders, as you can see that from the past poster writing about only the coding example of Java program it is because we are now focusing make a proper list of Java program which will help you're the readers to crack Java interview questions. so the next post is about most popular question which is asked in the JAVA interviews , Is how to remove duplicate elements from a String in Java.If you have not gone through the previous Java programs and also find them here.
So in this program which is am about to write we are dealing only with the string that contains alphabets not number . We have a string as ”pdbertasd” the output should be as “pdbertas”.
While Giving interview interviewer can ask to use any third party library or third party API to code these kind of questions , so we have design the answer accordingly.
public class JavaInHouseRemoveDuplicate{
String toRemove="myteststring";
public static void main(String[] args) {
String finalString=JavaInHouseRemoveDuplicate(toRemove);
System.out.println("Final String is : " + finalString);
public static String JavaInHouseRemoveDuplicate(String str) {
char[] tempStringString = str.toCharArray();
int length = tempString.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (tempString[i] == tempString[j]) {
int test = j;
for (int k = j + 1; k < length; k++) {
tempString[test] = tempString[k];
test++;
}
length--;
j--;
}
}
}
return String.copyValueOf(tempString).substring(0, length);
}
}
}
|
OutPut is :
Final String is :mytesring
if you have any questions or suggestions please comment below.
Post a Comment