How to replace only the surname and patronymic with " * "?

Viewed 36

Could you please help me? I have "name surname patronomyc". I only want to replace the "surname patronomyc" with " * ". I can only replace everything with " * ".

String s = "name surname patname";
System.out.println(s.replaceAll( "\\B.\\B", "*" ))

Output -- n ** e s****e p ****e

How to replace only the surname and patronymic with " * "?

Example: name s ***** e p ***** e

1 Answers

One way you can achieve this is by splitting the string into two and replacing the characters only on the second string, should look something like this:

String s = "name surname patname";

//splitting at a space character and setting limit of how many strings it is split into
String[] sArr = s.split(" ", 2); 

System.out.println(sArr[0] + " " + sArr[1].replaceAll("\\B.\\B", "*"));

this should have your desired output: name s*****e p*****e

Related