Replace all occurrences of specific char and get all options

I have a word on which I need to replace a certain symbol with an asterisk, but I need to get all replaced variants from this word. E.g. I want to replace the 'e' character with an asterisk with:

String word = telephone; 

but to get this list as a result:

 List of words = [t*lephone, tel*phone, telephon*, t*l*phone, t*lephon*, tel*phon*, t*l*phon*]; 

Is there a quick way to do this in Java?

+4
source share
1 answer

The following code will do this in a recursive manner:

 public static Set<String> getPermutations(final String string, final char c) { final Set<String> permutations = new HashSet<>(); final int indexofChar = string.indexOf(c); if (indexofChar <= 0) { permutations.add(string); } else { final String firstPart = string.substring(0, indexofChar + 1); final String firstPartReplaced = firstPart.replace(c, '*'); final String lastPart = string.substring(indexofChar + 1, string.length()); for (final String lastPartPerm : getPermutations(lastPart, c)) { permutations.add(firstPart + lastPartPerm); permutations.add(firstPartReplaced + lastPartPerm); } } return permutations; } 

It adds the original String to the output, therefore:

 public static void main(String[] args) { String word = "telephone"; System.out.println(getPermutations(word, 'e')); } 

Outputs:

 [telephone, t*lephone, tel*phone, t*l*phone, telephon*, t*lephon*, tel*phon*, t*l*phon*] 

But you can always call remove in the returned Set with the source word.

+5
source

All Articles