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.
The simplest is to use a regular expression:
String s = "abcdefg"
s = s.replaceFirst(".{4}$", "****"); => "abc****"
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) + "****";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With