Wednesday 5 August 2015

Replace spaces in a character array with %20

Suppose, you had character array, which contains some space. Your task is to replace each space with %20. Assume that the array has enough space at the end to accommodate the expanded string.


We can solve this problem using reverse approach. Find out last non-empty character, move it to array end. Apply this logic till starting of the array, whenever you found a space, update array with %20.
public class SpaceResolver {

 public static void replaceCharacters(char arr[]) {
  int i;

  /* Find first non-empty character */
  for (i = arr.length - 1; i >= 0; i--) {
   if (arr[i] != ' ')
    break;
  }

  int counter = arr.length - 1;
  for (int j = i; j > -1; j--) {
   if (arr[j] != ' ') {
    arr[counter] = arr[j];
    counter--;
    continue;
   }
   arr[counter--] = '0';
   arr[counter--] = '2';
   arr[counter--] = '%';
  }
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Test;

public class SpaceResolverTest {

 @Test
 public void test1() {
  char arr[] = { 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u',
    ' ', ' ', ' ', ' ' };
  char expected[] = { 'H', 'o', 'w', '%', '2', '0', 'a', 'r', 'e', '%',
    '2', '0', 'y', 'o', 'u' };

  SpaceResolver.replaceCharacters(arr);

  assertTrue(Arrays.equals(arr, expected));
 }
}


No comments:

Post a Comment