Contents

Clearing characters, how to clear the index corresponding to a value present in an array from a string (with.Java)

   Sep 17, 2023     2 min read

In this article, Clear characters, how to clear the index corresponding to a value existing in an array from a string (with.Java)

We’re going to learn by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem

Problem

Given a string my_string and an array of integers indices, write a solution function that removes the characters from my_string corresponding to the elements in indices and returns the concatenated string.

Example input and output

my_string: “apporoograpemmemprs”

indices: [1, 16, 6, 15, 0, 10, 11, 3]

result: “programmers”

Clear the letters of the index in indices and concatenate them to get “programmers”, so return that.

My solution to the problem

import java.util.*;
class Solution {
    public String solution(String my_string, int[] indices) {
        StringBuilder sb = new StringBuilder(my_string);
        Arrays.sort(indices);
        for(int i = indices.length - 1; i >= 0; i--){
           sb.deleteCharAt(indices[i]);
        }
        } return sb.toString();
    }
}
Solution.

This code deletes the character at the index corresponding to each element of the given integer array indices from the string my_string and returns the resulting string after deletion.

It creates a StringBuilder object, sb, to copy the contents of the input string, my_string. StringBuilder is an efficient class for manipulating strings.

Use Arrays.sort(indices); to sort the array of indices in ascending order. This arranges the indices to be deleted in order of lowest to highest number.

Use a loop to traverse from the last element to the first element of the indices array, that is, from high index to low index.

Delete the character at the index corresponding to indices[i] from the StringBuilder object sb by calling sb.deleteCharAt(indices[i]);. You delete from the highest index first, so the position of the preceding index is not changed.

After deleting the characters of all the indices, call sb.toString() to convert the contents of the StringBuilder object to a string and return it.

This will return a string with the characters of the indices in the indices array in my_string deleted.

What happens if you delete the string by index without sorting it?

I gave a little hint in the commentary, but if the leading index is pre-deleted from the string, the array will be filled with the strings remaining at the deleted index, causing the elements to swap positions and not giving the desired result.

So there you have it.