-2

I want to essentially replace part of substring that contains the "abc" with the *s. I want to do this using java8 (repeat() does not exist in java8).

String s = "abcdefgh"; 
String word1 = "abc";  
s = s.replaceAll(word1,"*"*word1.length());

output should be:

s = "***defgh"
f1sh
  • 11,489
  • 3
  • 25
  • 51
dsknjksad
  • 83
  • 4
  • You can build the replacement using a loop. – Chaosfire Jun 07 '22 at 13:18
  • how would that work because it still just replaces with only one star – dsknjksad Jun 07 '22 at 13:22
  • @dsknjksad not if you use a loop to generate multiple `*`s which is what Chaosfire suggested. – f1sh Jun 07 '22 at 13:27
  • Check [how to repeat a string](https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string.) – Chaosfire Jun 07 '22 at 13:29
  • 1
    Out of curiosity, is this for a form of text-censoring? Because users can quickly and easily `4bc` to get around these types of filters, and other solutions exist. – Rogue Jun 07 '22 at 13:50
  • 1
    @Rogue indeed, like `аbc` which does not match `abc`. – Holger Jun 07 '22 at 15:13
  • If you don't have the `repeat()` method available to you then perhaps use the [String.join()](https://www.w3resource.com/java-tutorial/string/string_join.php) method: `s = s.replace(word1, String.join("", java.util.Collections.nCopies(word1.length(), "*")));`. – DevilsHnd - 退職した Jun 08 '22 at 00:25

1 Answers1

1

You can do something like this:

String s = "abcdefgh";
String word1 = "abc";

String replace = "";
for (int i = 0; i < word1.length(); i++) {
    replace += "*";
}

s = s.replaceAll(word1,replace);
System.out.println(s);

gives:

***defgh
Benvorth
  • 7,416
  • 8
  • 49
  • 70