Thursday, August 29, 2013

Java - Avoid multiple occurrence of some character in a String

The following is a Java method/function which avoids multiple occurrence (in a row) of some character in an input String. The parameters to the method (i.e., inputs) to the method/function include: 
(1) input - The parent String under consideration 
(2) character - The character of which multiple occurrence (in a row) should be avoided.
public static String avoidMultipleOccurrence(String input, char character) {        
        if (input == null) {  
            return null;  
        if (input.length() == 0) {  
            return "";  
        StringBuilder output = new StringBuilder();  
        for (int idx = 1; idx < input.length(); idx++) {  
            if (Character.toString(input.charAt(idx)).equals(
                                                       "" + character)) {  
                if(input.charAt(idx) != input.charAt(idx-1)) {  
            } else {  
        return output.toString();  

Sample Input: "theeee insaneeeee teeeeechieeeee" 
Character selected: 'e' 
public static void main(String[] args) {
                "theeee insaneeeee teeeeechieeeee", 'e'));

Output: the insane techie


Post a Comment

Contact Form


Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...