Replacing last 4 characters with a "*"

A quick and easy method...

public static String replaceLastFour(String s) {
    int length = s.length();
    //Check whether or not the string contains at least four characters; if not, this method is useless
    if (length < 4) return "Error: The provided string is not greater than four characters long.";
    return s.substring(0, length - 4) + "****";
}

Now all you have to do is call replaceLastFour(String s) with a string as the argument, like so:

public class Test {
    public static void main(String[] args) {
        replaceLastFour("hi");
        //"Error: The provided string is not greater than four characters long."
        replaceLastFour("Welcome to StackOverflow!");
        //"Welcome to StackOverf****"
    }

    public static String replaceLastFour(String s) {
        int length = s.length();
        if (length < 4) return "Error: The provided string is not greater than four characters long.";
        return s.substring(0, length - 4) + "****";
    }
}

The simplest is to use a regular expression:

String s = "abcdefg"
s = s.replaceFirst(".{4}$", "****"); => "abc****"

Maybe an example would help:

String hello = "Hello, World!";
hello = hello.substring(0, hello.length() - 4);
// hello == "Hello, Wo"
hello = hello + "****";
// hello == "Hello, Wo****"

Tags:

Java

String