Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing last 4 characters with a "*"

Tags:

java

string

I have a string and I need to replace the last 4 characters of the string with a "*" symbol. Can anyone please tell me how to do it.

like image 552
Rahul Kalidindi Avatar asked Dec 17 '11 10:12

Rahul Kalidindi


2 Answers

The simplest is to use a regular expression:

String s = "abcdefg"
s = s.replaceFirst(".{4}$", "****"); => "abc****"
like image 151
KimvdLinde Avatar answered Nov 15 '22 20:11

KimvdLinde


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) + "****";
    }
}
like image 24
fireshadow52 Avatar answered Nov 15 '22 19:11

fireshadow52