0

I want to add prefix to every word in a given string. My code is :-

StringBuilder strColsToReturns  = new StringBuilder();
String strPrefix                = "abc.";
strColsToReturns.append(String.format(" %sId, %sname, %stype,", strPrefix, strPrefix, strPrefix));

This is fine, for small string, but I have a very large static string like this. So, this method of adding string prefix looks like a tedious method. Is there any other sophisticated way to achieve this.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97

1 Answers1

5

You can use replaceAll(regex, replacement). As regex we may want to select place which has

  • space or start of string before it
  • and non-space after it.

(we can use look-around mechanisms here)

So something like this should work:

String replaced = originalString.replaceAll("(?<=\\s|^)(?=\\S)", "abc.");

But if replacement can contain $ or \ characters you will need to escape them with \, or with Matcher.quoteReplacement(replacement) method.

String originalString = "foo bar baz";
String replaced = originalString.replaceAll("(?<=\\s|^)(?=\\S)", Matcher.quoteReplacement("abc."));
System.out.println(replaced);

Output: abc.foo abc.bar abc.baz

Pshemo
  • 122,468
  • 25
  • 185
  • 269