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();  
        output.append(input.charAt(0));        
        for (int idx = 1; idx < input.length(); idx++) {  
            if (Character.toString(input.charAt(idx)).equals(
                                                       "" + character)) {  
                if(input.charAt(idx) != input.charAt(idx-1)) {  
                    output.append(input.charAt(idx));  
                }  
            } else {  
                output.append(input.charAt(idx));  
            }  
        }  
        return output.toString();  
}

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

Output: the insane techie

Post a Comment

0 Comments