jroy8 jroy8 - 3 months ago 41
Java Question

Inserting letters into a string at every possible spot

I am looking to insert a single letter one by one into every possible index of a string.

For example the string


Would go
"ary" "bry" "cry" ... "zry" ... "ray" "rby" .... "rzy" ... "ra" "rb"

I am not sure how to begin, any help?

jay jay

Try this System.out.println("originaltext".replaceAll(".{1}","$0ry"));

The above is using the String replaceAll(String regex, String replacement) method - "Replaces each substring of this string that matches the given regular expression with the given replacement."

".{1}" - The regular expression used to find exactly one occurrence({1}) of any character(.)

"$0ry" - The replacement string with "$0" for the matched value followed by the required characters(ry).

This is repeated for all matches!