我试图创建一个创建数组并计算字符串中有多少个字符的函数,该函数区分大小写。
我只能使用 foreach
示例:
var_dump(count_char("H e l l o"));
// should returns array("H" => 1, "e" => 1, "l" => 2, "o" => 1)
var_dump(count_char("Hello World"));
// should returns array("H" => 1,"W" = 1, "d" => 1, "e" => 1, "l" => 3, "o" => 2, "r" = 1)
这是我的代码:
function count_char($str) {
foreach ($str as $key => $value) {
return strlen($value);
}
}
答案 0 :(得分:1)
使用关联的数组,只是通过字符串是最简单的方法......
function count_characters($str) {
$chars = str_split($str);
$char_counter = Array();
foreach($chars as $char)
if(!isset($char_counter[$char])) $char_counter[$char] = 1;
else $char_counter[$char] += 1;
return $char_counter;
}
print(json_encode(count_characters("Hello World"), JSON_PRETTY_PRINT)."\n");
如果要排除除ASCII字符([a-zA-Z]
)之外的所有内容:
function count_characters($str) {
$chars = str_split($str);
$char_counter = Array();
foreach($chars as $char)
if ((ord($char) >= 65 && ord($char) <= 90) ||
(ord($char) >= 97 && ord($char) <= 122)) {
if(!isset($char_counter[$char])) $char_counter[$char] = 1;
else $char_counter[$char] += 1;
}
return $char_counter;
}
print(json_encode(count_characters("Hello World... test This"), JSON_PRETTY_PRINT)."\n");
只排除空格:
function count_characters($str) {
$chars = str_split($str);
$char_counter = Array();
foreach($chars as $char)
if (ord($char) != 32) {
if(!isset($char_counter[$char])) $char_counter[$char] = 1;
else $char_counter[$char] += 1;
}
return $char_counter;
}
print(json_encode(count_characters("H e l l o W o r l d"), JSON_PRETTY_PRINT)."\n");
答案 1 :(得分:0)
你也可以使用array_count_values来完成这个技巧而不需要循环。
$ str ='Hello World';
$ str = str_replace(“”,“”,$ str);
$ chars = str_split($ str);
$ ret = array_count_values($ chars);
的print_r($ RET);
答案 2 :(得分:0)
这些是您的任务中的步骤:
(有几种方法可以做到这一点,你可以从下一个问题的答案中看到。)因为你的作业foreach()
循环似乎有些压力,所以我会做提供以下内容:
代码:(Demo)
function count_char($str) {
$chars = str_split($str); // split the string between each character
$result = array();
foreach($chars as $char) {
if (ctype_alpha($char)) { // only store letters
if (!isset($result[$char])) {
$result[$char] = 1; // instantiate the letter in the result
} else {
++$result[$char]; // increment the tally for the letter
}
}
}
return $result;
}
var_dump(count_char("Hello World"));
也就是说,正则表达式可以一次执行前两个操作:
$letters = preg_split('~[^a-z]*~i', $str, -1, PREG_SPLIT_NO_EMPTY);
正如AndrewK所提及的那样array_count_values()
是一个逻辑/直接选择:
$counts = array_count_values($letters);