【随手练习】从字符串中找出最长的单词(TypeScript实现)
如题,给出一个字符串,里面包含若干单词,单词之间用空格分隔。找出字符串中长度最长的单词。
function findTheLongestWord(inputStr:string){
if(inputStr === undefined || inputStr.trim() === ""){
return ""
}
inputStr = inputStr.trim();
console.log(`输入:${inputStr}`);
let strLength = inputStr.length;
//当前遍历指针位置
let position = 0;
//开始记录单词长度的标志位
let startFlag = false;
//单词开始的位置
let wordStartPos = 0;
//单词结束的位置
let wordEndPos = wordStartPos;
//最长单词长度
let maxWordLength = 0;
//最长单词
let maxWord = "";
while(position < strLength){
let currentChar = inputStr.charAt(position);
// 出现第一个不为空的字符时,同时没有开始记录单词长度,就立即开始记录。
if(currentChar !== " "){
if(!startFlag){
startFlag = true;
wordStartPos = position;
}else{
wordEndPos = position;
}
}
// 出现空格就判断一下。特殊情况:字符串最后一个单词后面已经没有空格了
if(currentChar === " " || position === strLength - 1){
// 如果已经处于记录长度的状态,就开始长度判断
let currentWordLength = 0;
if(startFlag){
wordEndPos = position;
if(position === strLength - 1){
wordEndPos++;
}
startFlag = false;
currentWordLength = wordEndPos - wordStartPos;
if(currentWordLength > maxWordLength){
maxWordLength = currentWordLength;
maxWord = inputStr.substring(wordStartPos, wordEndPos);
}
//重置单词记录状态
startFlag = false;
console.log(`当前单词:${inputStr.substring(wordStartPos, wordEndPos)} 长度:${currentWordLength}`);
}
}
position++;
}
console.log(`最长单词是:${maxWord},长度为:${maxWordLength}`);
}
const str = " let currentWordLength = wordEndPos - wordStartPos; 1234567890abcdefghijklmn";
findTheLongestWord(str);

墨笑
如果我的文章能帮到你,还请不吝打赏,五块三块不嫌多,一块五毛不嫌少
版权属于:
墨笑的精神小憩之地 的博客
本文链接:
https://www.whisperdiary.cn/index.php/archives/69/
作品采用:
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可
推荐阅读
评论已关闭