在重复字符数的下一行中打印不同的字符并打印星号
Print distinct characters and print stars in next rows that number of characters are repeated
我有一个字符串$string = "CONSTANTMAINONE";
我想打印不同的字符,并在重复字符数的下一行中打印星号。
C O N S T A M I E
* * * * * * * * *
* * * *
*
*
我试过的
Loop the characters
Add the character as a key and count as a value
Then printed, but that output is not coming vertically and the question should be do not use table
or pre
tags
$string = "CONSTANTMAINONE";
$repeated_char = [];
for($i=0; $i<=strlen($string);$i++){
if(!array_key_exists($string[$i], $repeated_char)){
$repeated_char[$string[$i]] = 1;
}else{
$repeated_char[$string[$i]] += 1;
}
}
到目前为止,输出为
C => 1
o => 1
N => 4
s => 1
T => 1
..etc..,
然后,打印字符
foreach($repeated_char as $key=>$val){
echo $key. " ";
for($j=0; $j<$val; $j++){
echo "*";
}
echo "<br/>";
}
所以,我的代码的最终输出
C *
o **
N ****
S *
T **
A **
M *
I *
E *
此答案来自第一次修订:
https://whosebug.com/revisions/28536477/1
这应该适合你:
(这里我使用 str_split()
to create a array out of the string. After this i count all array values with array_count_values()
。然后它只是一个简单的打印事情。首先我打印所有唯一值,然后我打印开始并递减 tmp 数组中的值)
<?php
$string = "CONSTANTMAINONE";
$array = str_split($string);
$count = array_count_values($array);
$tmp = $count;
echo "<table border='1'><tr>";
foreach($count as $k => $v)
echo "<td>" . $k . "</td>";
echo "</tr>";
for($i = 0; $i < max($count); $i++) {
echo "<tr>";
foreach($tmp as $k => $v) {
if($v >= 1)
echo "<td>*</td>";
else
echo "<td></td>";
$tmp[$k]--;
}
echo "</tr>";
}
echo "</table>";
?>
输出:
C O N S T A M I E
* * * * * * * * *
* * * * * * * * *
* * * *
*
我有一个字符串$string = "CONSTANTMAINONE";
我想打印不同的字符,并在重复字符数的下一行中打印星号。
C O N S T A M I E
* * * * * * * * *
* * * *
*
*
我试过的
Loop the characters Add the character as a key and count as a value Then printed, but that output is not coming vertically and the question should be do not use
table
orpre
tags
$string = "CONSTANTMAINONE";
$repeated_char = [];
for($i=0; $i<=strlen($string);$i++){
if(!array_key_exists($string[$i], $repeated_char)){
$repeated_char[$string[$i]] = 1;
}else{
$repeated_char[$string[$i]] += 1;
}
}
到目前为止,输出为
C => 1
o => 1
N => 4
s => 1
T => 1
..etc..,
然后,打印字符
foreach($repeated_char as $key=>$val){
echo $key. " ";
for($j=0; $j<$val; $j++){
echo "*";
}
echo "<br/>";
}
所以,我的代码的最终输出
C *
o **
N ****
S *
T **
A **
M *
I *
E *
此答案来自第一次修订:
https://whosebug.com/revisions/28536477/1
这应该适合你:
(这里我使用 str_split()
to create a array out of the string. After this i count all array values with array_count_values()
。然后它只是一个简单的打印事情。首先我打印所有唯一值,然后我打印开始并递减 tmp 数组中的值)
<?php
$string = "CONSTANTMAINONE";
$array = str_split($string);
$count = array_count_values($array);
$tmp = $count;
echo "<table border='1'><tr>";
foreach($count as $k => $v)
echo "<td>" . $k . "</td>";
echo "</tr>";
for($i = 0; $i < max($count); $i++) {
echo "<tr>";
foreach($tmp as $k => $v) {
if($v >= 1)
echo "<td>*</td>";
else
echo "<td></td>";
$tmp[$k]--;
}
echo "</tr>";
}
echo "</table>";
?>
输出:
C O N S T A M I E
* * * * * * * * *
* * * * * * * * *
* * * *
*