Posted On: Dec 22, 2020
A Java program to remove consecutive duplicate characters in a string is as follows:
public class Hello { public static void main(String[] args) { String str1 = "Online interviews"; System.out.println(removeDuplicateChars(str1)); } private static String removeDuplicateChars(String sourceStr) { // Store encountered letters in this string. char[] chrArray = sourceStr.toCharArray(); String targetStr = ""; // Loop over each character. for (char value : chrArray) { // See if character is in the target if (targetStr.indexOf(value) == -1) { targetStr += value; // Use StringBuilder as shown below } } return targetStr; } }
Output :
Onlie trvw
You could use StringBuilder as shown below :<?p>
private static String removeDuplicates(String str) { StringBuilder sb = new StringBuilder(); char[] arr = str.toCharArray(); for (char ch : arr) { if (sb.indexOf(String.valueOf(ch)) != -1) continue; else sb.append(ch); } return sb.toString(); }
Never Miss an Articles from us.
Multithreading is a programmable approach to achieve multitasking. Multithreading in Java is a process of executing multiple threads cumulatively. A thread is the smallest unit of processing which is ...
In Java, intern() is a native method of the String class. The String.intern () returns a reference to the equal string literal present in the string pool. The intern () method is applicable to String ...
A Java collection framework is an architecture that was added to Java 1.2 version. The Collection Framework provides a well-designed set of classes and interfaces for storing and manipulating a group ...