替换所有出现的某些字符并获取所有变体

时间:2013-03-26 16:58:55

标签: java string replace variations

我有一个单词,我需要用星号替换某个字符,但我需要从这个单词中获取所有替换的变体。例如。我想用星号替换字符'e':

String word = telephone;

但要获得此列表:

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

在Java中有快速的方法吗?

1 个答案:

答案 0 :(得分:5)

以下代码将以递归方式执行此操作:

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;
}

它将原始String添加到输出中,因此:

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

输出:

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

但是,您始终可以使用原始字词在返回的remove上致电Set