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!