Search code examples
javastringstringbuilder

Insert a character before and after all letters in a string in Java


I want to insert a % character before after every letter in a string, but using StringBuilder to make it fast.

For example, if a string is 'AA' then it would be '%A%A%'. If it is 'XYZ' then it would be '%X%Y%Z%'


Solution

  • String foo = "VWXYZ";
    foo = "%" + foo.replaceAll("(.)","$1%");
    System.out.println(foo);
    

    Output:

    %V%W%X%Y%Z%

    You don't need a StringBuilder. The compiler will take care of that simple concatenation prior to the regex for you by using one.

    Edit in response to comment below:

    replaceAll() uses a Regular Expression (regex).

    The regex (.) says "match any character, and give me a reference to it" . is a wildcard for any character, the parenthesis create the backreference. The $1 in the second argument says "Use backreference #1 from the match".

    replaceAll() keeps running this expression over the whole string replacing each character with itself followed by a percent sign, building a new String which it then returns to you.