【问题标题】:Java equivalent of PHP str_word_count? [duplicate]Java相当于PHP str_word_count? [复制]
【发布时间】:2013-03-07 23:42:05
【问题描述】:

注意:我在这里不是在寻找 Java 中的字数统计算法。我在问在PHP源代码中哪里可以找到str_word_count

我希望将str_word_count PHP 函数重新创建(如果可能,逐行)作为 Java 方法:

public class PhpWordCounter {
    public int strWordCount(String str) {
        // The exact algorithm used in PHP's str_word_count here...
        // The str_word_count method takes an optional parameter
        // "format", which, if 0, returns the number of words.
        // This is the portion of the routine that I will actually
        // be mimicking.
    }
}

我刚刚下载了 PHP 5.3.23 的源代码(tarball)并解压。我寻找str_word_count 并没有找到任何东西,所以我什至不确定要查找什么,更不用说要搜索什么文件了。有人有什么想法吗?提前致谢!

【问题讨论】:

  • 好吧,如果您的目标是精确复制,那么返回类型肯定不是是一个int。跨度>
  • Good catch @Perception (+1) - 我应该提到 format 默认情况下被视为 0(因此将单词数作为整数类型返回)。所以我不会担心str_word_count 中处理任何其他format 类型的任何部分。
  • PHP 源代码可用,用 C 编写。如果您想复制确切的算法,那就从这里开始。
  • 对,但就像我说的,我找了str_word_count,但没有找到...
  • @DirtyMikeAndTheBoys - 看起来实现在 php-5.x.xx/ext/standard/string.c 中。或者至少是其中的一部分。您是否考虑过使用Apache Commons Lang 3 StringUtils?它有一个 countMatches 方法已经完成了这个逻辑。

标签: java php word-count


【解决方案1】:

你应该看起来更好:) 它应该在最新的稳定分支http://www.php.net/manual/en/function.str-word-count.php 中可用

find . -type f -exec grep -l 'str_word_count' {} \;

./ext/standard/php_string.h
./ext/standard/tests/strings/str_word_count1.phpt
./ext/standard/tests/strings/str_word_count.phpt
./ext/standard/basic_functions.c
./ext/standard/string.c

【讨论】:

  • 谢谢@tlnse 这正是我所需要的
【解决方案2】:

不知道有没有现成的功能... 但: 按空格将字符串拆分为数组 获取数组的长度

String vals[] = myString.split("\s+"); int wordCount = vals.length;

【讨论】:

  • 谢谢,但请查看我的更新 - 我不是要 Java 字数统计算法。我在问在 PHP 源代码中哪里可以找到 str_word_count。
猜你喜欢
  • 1970-01-01
  • 2016-03-06
  • 2015-04-21
  • 1970-01-01
  • 2020-04-13
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
相关资源
最近更新 更多