Replacing exclamation

Language: Java

Task:

Given a string parameter s and an integer parameter n, replace n number of exclamation marks in s from left to right. E.g. Kata.remove(“Hi!”,1) will return “Hi” whilst Kata.remove(“!Hel!lo!”,2) will return “Hello!” (removing the first two exclamation marks).

Parameters:

s –> a string where exclamation marks have to be replaced

n –> a given number of exclamation marks that have to be removed

Code:

public Kata(String s, int n) {
    }
    public static String remove(String s, int n){
        String newWord = "";
        //Creates a loop to run through s
        for (int i = 0; i<s.length(); i++) {
            //Changes the latest character of the string into a unicode
            int code = s.charAt(i);
            //If the unicode is 33 (exclamation mark) and n number of exclamation marks has not been removed,
            //it jumps the character and takes away one from n as an exclamation mark will have been removed
            if (code == 33 && n>0){
                n--;
                continue;
            }
            //If the character is not an exclamation mark or all of the required exclamation marks have been removed
            //it adds this variable to newWord that will be returned at the end.
            newWord = newWord + s.charAt(i);
        }
        return newWord;
    }

Improvements:

The two methods that could have been used to improve this are .contains(“!”) instead of using Unicode and extracting a character with charAt. This could be combined with .replaceFirst(“!”,””) in order to removed the exclamation marks one at a time from the left.