【问题标题】:Longest word in a string字符串中最长的单词
【发布时间】:2011-01-04 22:35:07
【问题描述】:

如何获取字符串中最长的单词?

例如。

$string = "Where did the big Elephant go?";

返回"Elephant"

【问题讨论】:

  • 到目前为止你尝试过什么?虽然有人可能会给你答案,但如果你先尝试一些东西,你会学到更多。 (而且,如果你表明你已经深思熟虑,你更有可能得到更好的答案。)

标签: php string


【解决方案1】:

遍历字符串中的单词,跟踪目前最长的单词:

<?php
$string = "Where did the big Elephant go?";
$words  = explode(' ', $string);

$longestWordLength = 0;
$longestWord = '';

foreach ($words as $word) {
   if (strlen($word) > $longestWordLength) {
      $longestWordLength = strlen($word);
      $longestWord = $word;
   }
}

echo $longestWord;
// Outputs: "Elephant"
?>

可以提高一点效率,但你明白了。

【讨论】:

  • 你在 15 秒内就写好了?!
  • @JMCCreative:我太棒了。
  • @Tomalak 你的厉害之处应该是 $longestWord 而不是 $word ;)
  • @FrankNwoko:另外你应该知道这里的“字长”包括任何标点符号。您可以使用 PHP 中的相关字符串函数去除标点符号。我会让你自己研究一下。
  • @mvds:好吧,我放弃了。这是一个查找时间最长的示例。
【解决方案2】:

更新:这是另一种更短的方法(这绝对是新的;)):

function reduce($v, $p) {
    return strlen($v) > strlen($p) ? $v : $p;
}

echo array_reduce(str_word_count($string, 1), 'reduce'); // prints Elephant

与已经发布的类似,但使用str_word_count 提取单词(只需在空格处分割,标点符号也会被计算在内):

$string = "Where did the big Elephant go?";

$words = str_word_count($string, 1);

function cmp($a, $b) {
    return strlen($b) - strlen($a);
}

usort($words, 'cmp');

print_r(array_shift($words)); // prints Elephant

【讨论】:

  • +1 用于使用str_word_count()。不过,为了简洁起见,我会立即将该函数放在对 usort() 的调用中。我是 jQuery 约定的奴隶!
  • 我不喜欢创建函数(并污染符号表)的需要! create_function 会解决这个问题,但事情会非常冗长。
  • @Tomalak Geret'kal:我也不喜欢它,但有时它是不可避免的(不是说这里就是这种情况)。
  • @Felix 我不确定你没有引用你的数组是什么意思。我建议usort( $words, function( $a, $b ) { /* code */ } ); 应该可以正常工作。这就是@lonesomeday 采用的方法。
  • @Jonathan Sampson:啊,我以为您的意思是将函数 str_word_count 放入 usort :D 我想直接传递函数,但我仍然倾向于以 5.2 风格给出答案。它更通用,知道 PHP 5.3 的人应该能够对其进行转换...
【解决方案3】:

这个怎么样——按空格分割,然后按字符串长度排序,然后抓取第一个:

<?php

$string = "Where did the big Elephant go?";

$words = explode(' ', $string);

usort($words, function($a, $b) {
    return strlen($b) - strlen($a);
});

$longest = $words[0];

echo $longest;

编辑如果要排除标点符号,例如:“大象去哪儿了?”,可以使用preg_split

$words = preg_split('/\b/', $string);

【讨论】:

  • @Tomalak 确实,它有点慢。尽管如此,它仍然是一种替代方案,甚至可能更漂亮的解决方案。
【解决方案4】:

这是另一个解决方案:

$array = explode(" ",$string);
$result = "";
foreach($array as $candidate)
{
if(strlen($candidate) > strlen($result))
$result = $candidate
}
return $result;

【讨论】:

    【解决方案5】:

    在处理文本时这是一个非常有用的函数,因此为此目的创建一个 PHP 函数可能是个好主意:

    function longestWord($txt) {
        $words = preg_split('#[^a-z0-9áéíóúñç]#i', $txt, -1, PREG_SPLIT_NO_EMPTY);
        usort($words, function($a, $b) { return strlen($b) - strlen($a); });
        return $words[0];
    }
    echo longestWord("Where did the big Elephant go?");
    // prints Elephant
    

    在这里测试这个功能:http://ideone.com/FsnkVW

    【讨论】:

      【解决方案6】:

      一种可能的解决方案是在一个公共分隔符(例如空格)上拆分句子,然后遍历每个单词,只保留对最大单词的引用。

      请注意,这将找到第一个最大的单词。

      <?php
      function getLargestWord($str) {
        $strArr = explode(' ', $str); // Split the sentence into an word array
        $lrgWrd = ''; // initial value for comparison
        for ($i = 0; $i < count($strArr); $i++) {
          if (strlen($strArr[$i]) > strlen($lrgWrd)) { // Word is larger
            $lrgWrd = $strArr[$i]; // Update the reference
          }
        }
        return $lrgWrd;
      }
      // Example:
      echo getLargestWord('Where did the big Elephant go?');
      ?>
      

      【讨论】:

      • 虽然提供的代码回答了问题,但您可以假设阅读问题的人不会理解它,请提供 cmets 解释您在做什么,因为这个更简单的问题。
      猜你喜欢
      • 2022-01-01
      • 2018-04-18
      • 2020-03-04
      • 2020-08-22
      • 2018-11-25
      • 1970-01-01
      • 2014-10-27
      • 2016-06-14
      • 1970-01-01
      相关资源
      最近更新 更多