Remove characters from consecutive runs of the same character, where the length of the run is greater than the input parameter

Remove characters from consecutive runs of the same character, where the length of the run is greater than the input parameter

Use java and Write a method that takes two parameters, a string and an integer.
The Method will return another string that is similar to the input string, but with certain characters removed.
The code should compile and run with Junits

It’s going to remove characters from consecutive runs of the same character, where the length of the run is greater than the input parameter.

Eg: “aaab”, 2 = “aab”
Eg: “aabb”, 1 = “ab”
Eg: “aabbaa”, 1 = “aba”

Solution:

Java class:

package coding.test;

public class RemoveCharacter {

	public String removeConsecutieve(String value, int value2) {

		char c[] = value.toCharArray();
		char prevChar = '\u0000';
		int currentChar = 0;
		StringBuilder stringBuilder = new StringBuilder();

		for (char d : c) {

			if (d == prevChar) {
				currentChar = currentChar + 1;
			} else {
				currentChar = 0;
				prevChar = d;
			}

			if (currentChar < value2) {
				stringBuilder.append(d);
			}

		}

		return stringBuilder.toString();

	}

}

Junit class:

package coding.test;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class RemoveCharacterTest {
	
	RemoveCharacter removeCharacter;

	@Before
	public void setUp() throws Exception {
		removeCharacter = new RemoveCharacter();
	}

	@After
	public void tearDown() throws Exception {
		removeCharacter = null;
	}

	@Test
	public void testRemoveConsecutieve() {
		
		Assert.assertEquals("aab", removeCharacter.removeConsecutieve("aaab", 2));
		
		Assert.assertEquals("ab", removeCharacter.removeConsecutieve("aabb", 1));
		
		Assert.assertEquals("aba", removeCharacter.removeConsecutieve("aabbaa", 1));
		
	}

}
One thought on “Remove characters from consecutive runs of the same character, where the length of the run is greater than the input parameter”
  1. There is a bug in the code when the first character is ‘\u0000’.
    Eg: “\u0000\u0000aabbaa”, 1.
    The code would return “aba”, but the correct result should be “\u000aba”.

Leave a Reply

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