【问题标题】:PHP - all combination upper and lower case characters of stringPHP - 字符串的所有组合大小写字符
【发布时间】:2017-11-27 05:20:26
【问题描述】:

我尝试获取字符串的所有组合大小写字符。例如我的字符串是abc。我需要得到这样的结果,字符串的 3 个字符的所有组合:(2^0) x (2^1) x (2^2) = 8:

abc
Abc
ABc
ABC
aBC
abC
AbC
aBc

我的代码是这样的,但我有一个问题,我的代码有重复的情况,不返回 AbCaBc

<?php
function opposite_case($str) 
{ 
    if(ctype_upper($str)) 
    { 
        return strtolower($str); 
    } 
    else 
    { 
        return strtoupper($str); 
    } 
} 

$str = "abc";

for($i = 0 ; $i < strlen($str) ; $i++)
{
    for($j = 0 ; $j < strlen($str) ; $j++) 
    {
        $str[$j] = opposite_case($str[$j]);
        echo $str."<br>"; 
    }
}
?>

【问题讨论】:

标签: php combinations uppercase lowercase


【解决方案1】:

一些代码转储,其中包含一些 cmets 以作为很好的衡量标准。这是从 Java 实现转换而来的 - https://stackoverflow.com/a/6785649/296555

http://sandbox.onlinephpfunctions.com/code/aadefa26561a0e33c48fd1d147434db715c8fc59

2020 年 11 月 - 此答案已在 2 个地方更新。有关详细信息,请参阅修订历史记录。

<?php

function calculatePermutations($text) {

    $permutations = array();
    $chars = str_split($text);
    
    // Count the number of possible permutations and loop over each group 
    for ($i = 0; $i < 2 ** strlen($text); $i++) {
        
        // Loop over each letter [a,b,c] for each group and switch its case
        for ($j = 0; $j < strlen($text); $j++) {
            
            // isBitSet checks to see if this letter in this group has been checked before
            // read more about it here: http://php.net/manual/en/language.operators.bitwise.php
            $permutations[$i][] = (isBitSet($i, $j)) 
                ? strtoupper($chars[$j]) 
                : $chars[$j];
        }
    }
    
    return $permutations;
}

function isBitSet($n, $offset) {
  return ($n >> $offset & 1) != 0;
}

print_r(calculatePermutations('abc'));

【讨论】:

  • 谢谢亲爱的。几秒钟前,我看到了这个 Java 注释并将其转换为 PHP。再次感谢。
  • 这有点旧,但因为它是这里的热门搜索结果之一。虽然最初的 Java 实现是正确的,但这个似乎有两个错误。 1) 初始 for 循环应该从 0 开始,否则您最终会丢失结果中的初始字符串。 2) 可能的排列数是字符串长度的 2 次方,而不是相反。
  • @DiogoTeixeira - 你确实是对的。感谢您指出。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2015-02-20
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 2012-07-20
  • 2019-08-04
  • 1970-01-01
相关资源
最近更新 更多