查找字符串中最长的单词

题目

返回给出的句子中最长的单词的长度。

你的返回应该是一个数字。

 

要求

  1. findLongestWordLength("The quick brown fox jumped over the lazy dog")应该返回一个数字。
  2. findLongestWordLength("The quick brown fox jumped over the lazy dog")应该返回 6。
  3. findLongestWordLength("May the force be with you")应该返回 5。
  4. findLongestWordLength("Google do a barrel roll")应该返回 6。
  5. findLongestWordLength("What is the average airspeed velocity of an unladen swallow")应该返回 8。
  6. findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")应该返回 19。

代码

function findLongestWordLength(str) {
  let strArr = str.split(' ')
  let temp = strArr[0]
  for(let i = 1;i < strArr.length;i++) {
    temp.length < strArr[i].length ? temp = strArr[i] :''
  }
  return temp.length;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

 

这里提供两个代码示例,分别是C++和C#语言的实现方法。 C++代码示例: 该程序通过遍历字符串的每个字符,将单词保存在一个字符数组,并在遇到空格、逗号或句号时将其作为一个单词结束。然后,它将比较每个单词的长度,找到最长单词并输出。 C++代码如下: ``` #include <iostream> #include <cstring> using namespace std; //查找字符串最长的一个单词 void FindLongestWord(string &s){ int maxLength = -1;//保存最长字符串的长度 int cnt = 0;//保存word字符串的游标 char word[101],longest[101];//word保存遍历的单词,longest保存最长单词 for(int i = 0; i < s.length(); i++){ if(s[i] != ' ' && s[i] != ',' && s[i] != '.'){ word[cnt++] = s[i];//保存单词 } if(s[i] == ' ' || s[i] == ',' || s[i] == '.'){ if(maxLength < cnt){//如果是最长单词,保存至longest maxLength = cnt; for(int j = 0; j < maxLength; j++){ longest[j] = word[j]; } } cnt=0; } } cout<<"原始字符串:\n"<<s<<endl; cout<<"最长单词:"<<endl; for(int i = 0; i < maxLength; i++) cout<<longest[i]; } int main() { string str; getline(cin,str); FindLongestWord(str); return 0; } ``` C#代码示例: 该程序使用C#语言的ArrayList类来保存所有最长单词,并输出最长单词的长度和数量。 C#代码如下: ``` using System; using System.Collections; class Program { static void Main(string[] args) { Console.WriteLine("请输入字符串:"); string inputString = Console.ReadLine(); Program p = new Program(); ArrayList al = p.GetLongestWord(inputString); Console.WriteLine("最长单词是:"); for (int m = 0; m < al.Count; m++) { Console.WriteLine(al[m]); } string longestWord = (string)al[0]; Console.WriteLine("最长单词的长度为:{0}", longestWord.Length); Console.WriteLine("最长单词的数量为:{0}", p.GetLongestWord(inputString).Count); Console.ReadKey(); } public ArrayList GetLongestWord(string inputString) { ArrayList al = new ArrayList(); string[] words = inputString.Split(' ', ',', '.'); int maxLength = 0; foreach (string word in words) { if (word.Length > maxLength) { maxLength = word.Length; al.Clear(); al.Add(word); } else if (word.Length == maxLength) { al.Add(word); } } return al; } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值