Method to Remove Consecutive Repeating Characters from a String in Java

Recently I came across a problem that I required to allow a maximum of 2 consecutive repeating characters in a String in a Java application. For that, I couldn’t find any builtin method. So I wrote a generalized utility method to remove more than a specified number of consecutive repeating characters from a String. The function is following

public static String removeConsecutiveCharactersInString(String str, int maxConsecutiveAllowedCount) {
	       StringBuilder builder = new StringBuilder(str); // use StringBuilder for memory optimization
	       for (int i=0;i<builder.length();i++) {
	           int foundCount = 0;
	           for (int j=i-1;j>=0;j--) {
	               if (builder.charAt(i) == builder.charAt(j)) {
	                   foundCount++;
	                   if (foundCount >= maxConsecutiveAllowedCount) {
	                       builder.deleteCharAt(i);
	                       i--;
	                       break;
	                   }
	               } else {
	                   break;
	               }
	           }
	       }
	       return builder.toString();
	   }

Explanation

This method takes 2 parameters. The first parameter is the String from which you want to remove consecutive characters. The second parameter is the count of the maximum number of allowed consecutive characters. So this method removes the specified number of consecutive characters from the string and returns the resulting string. For example, If I call this function for the string "abceeed" with maxConsecutiveAllowedCount = 2. It would return "abceed", as "e" appears more than 2 times consecutively. Following is the way, how you can call this method

Example Call

String str = removeConsecutiveCharactersInString("aabccccabbadewed",2);
System.out.println(str);
Output: aabccabbadewed

That’s it! This is how you can remove consecutive repeating characters from a String 🙂

Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

One thought on “Method to Remove Consecutive Repeating Characters from a String in Java

  1. An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.