Zor*_*ski 4 java string replace variations
我有一个单词,我需要用星号替换某个字符,但我需要从这个单词中获取所有替换的变体.例如.我想在星号中用星号替换字符'e':
String word = telephone;
Run Code Online (Sandbox Code Playgroud)
但要获得此列表:
List of words = [t*lephone, tel*phone, telephon*, t*l*phone, t*lephon*, tel*phon*, t*l*phon*];
Run Code Online (Sandbox Code Playgroud)
在Java中有快速的方法吗?
以下代码将以递归方式执行此操作:
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;
}
Run Code Online (Sandbox Code Playgroud)
它将原始内容添加String到输出中,因此:
public static void main(String[] args) {
String word = "telephone";
System.out.println(getPermutations(word, 'e'));
}
Run Code Online (Sandbox Code Playgroud)
输出:
[telephone, t*lephone, tel*phone, t*l*phone, telephon*, t*lephon*, tel*phon*, t*l*phon*]
Run Code Online (Sandbox Code Playgroud)
但是你可以随时使用原始单词调用remove返回Set的内容.
| 归档时间: |
|
| 查看次数: |
279 次 |
| 最近记录: |