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%’
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Output:
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$1in 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.