Home  >  Article  >  Web Front-end  >  How to find the longest word in a string

How to find the longest word in a string

一个新手
一个新手Original
2017-09-08 14:22:152261browse

function findLongestWord(str) {
    //首先将字符串转换成数组,以空格为分割点
   var  arr = str.split(" ");
   //根据单词的长度  由长到短排列
   var t=0;
   for(var i=0;i<arr.length;i++){
       for(var j=0;j<arr.length;j++ )
       {
           if (arr[i].length > arr[j].length) {  
                    t = arr[i];  
                    arr[i] = arr[j];  
                    arr[j] = t;  
                }  
       }
   }
   //返回最长的单词长度
return arr[0].length;
}
//调用函数
findLongestWord("i am your girlfriend");

The above is the detailed content of How to find the longest word in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn