Replacing last 4 characters with a "*"
Solution 1
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) + "****";
}
}
Solution 2
The simplest is to use a regular expression:
String s = "abcdefg"
s = s.replaceFirst(".{4}$", "****"); => "abc****"
Solution 3
Maybe an example would help:
String hello = "Hello, World!";
hello = hello.substring(0, hello.length() - 4);
// hello == "Hello, Wo"
hello = hello + "****";
// hello == "Hello, Wo****"
Solution 4
public class Model {
public static void main(String[] args) {
String s="Hello world";
System.out.println(s.substring(0, s.length()-4)+"****");
}
}
Solution 5
You can use substring for this.
String str = "mystring";
str = str.substring(0,str.length()-4);
str = str + "****";
So substring takes two parameter.
substring(beginIndex, endIndex);
So, if you call a substring method in a string, It creates a new String that begins from beginIndex inclusive and endIndex exclusive. For example:
String str = "roller";
str = str.substring(0,4);
System.out.Println("str");
OUTPUT :
roll
so it starts from the beginIndex until the endIndex - 1.
If you want to know more about substring, visit http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Hope this helps.
Rahul Kalidindi
Solutions Architect and Dev Android iOS Mobile Apps Chatbots
Updated on November 21, 2020Comments
-
Rahul Kalidindi over 3 years
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.
-
Opeyemi Sanusi over 5 yearsnot exactly what i was looking for but it helped me figure out what i was looking for