多字节安全计数字符串中的不同字符
我不想找到一种智能且有效的方法来计算一个字符串中有多少个不同的字母字符。示例:
$str = "APPLE";
echo char_count($str) // should return 4, because APPLE has 4 different chars 'A', 'P', 'L' and 'E'
$str = "BOB AND BOB"; // should return 5 ('B', 'O', 'A', 'N', 'D').
$str = 'PLÁTANO'; // should return 7 ('P', 'L', 'Á', 'T', 'A', 'N', 'O')
它应该支持 UTF-8 字符串!
I wan't to find a smart and efficient way of counting how many different alpha characters are in one string. Example:
$str = "APPLE";
echo char_count($str) // should return 4, because APPLE has 4 different chars 'A', 'P', 'L' and 'E'
$str = "BOB AND BOB"; // should return 5 ('B', 'O', 'A', 'N', 'D').
$str = 'PLÁTANO'; // should return 7 ('P', 'L', 'Á', 'T', 'A', 'N', 'O')
It should support UTF-8 strings!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您正在处理 UTF-8(您确实应该考虑这一点,恕我直言),则所有发布的解决方案(使用 strlen、str_split 或 count_chars)都不起作用,因为它们都将一个字节视为一个字符(对于显然是 UTF-8)。
如果你想扔掉所有非单词字符:
If you're dealing with UTF-8 (which you really should consider, imho) none of the posted solutions (using strlen, str_split or count_chars) will work, as all of them treat one byte as one character (which is not true for UTF-8, obviously).
If you want to throw out all non-word characters:
只需使用 count_chars:
从
count_chars()< 返回的数组/code> 还会告诉您字符串中每个字符有多少个。
Just use count_chars:
The array returned from
count_chars()
will also tell you how many of each character are in the string.count_chars 返回所有 ASCII 字符的映射,告诉您字符串中每个字符的数量。这是您自己实施的起点。
count_chars returns a map of all the ascii characters, telling you how many of each there are in the string. Here's a starting point for your own implementation.
这是一个使用关联数组的魔力来完成此操作的函数。以线性时间工作。 (大O =
log(n)
)Here's a function that will do it, using the magic of associative arrays. Works in linear time. (big O =
log(n)
)我的看法是,
这将为您提供一个唯一字母的关联数组作为键,出现次数作为值。
如果你对出现的次数不感兴趣,
My take on it,
This will give you an associative array of unique letters as the key, and the number of occurrences as the value.
If you are not interested in the number of occurrences,