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 & duplicate 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.

Following is the Java code if you are looking for Kotlin code, you can find it here.

Method to Remove Consecutive Characters from a String in Java

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. This String is then converted into StringBuilder for memory optimization purposes. The second parameter is the count of the maximum number of allowed consecutive characters. So this method removes the specified number of consecutive & duplicate 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 🙂

You can also find other useful helping materials and tutorials in our Coding Articles & Tutorials Knowledge Base.

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

2 thoughts 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

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

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

%d bloggers like this: