在没有数组或方法的字符串中查找最长的单词可以通过以下步骤实现:
以下是一个示例的JavaScript代码实现:
function findLongestWord(str) {
let longestWord = "";
let longestLength = 0;
let currentWord = "";
let currentLength = 0;
for (let i = 0; i <= str.length; i++) {
if (str[i] === " " || i === str.length) {
if (currentLength > longestLength) {
longestWord = currentWord;
longestLength = currentLength;
}
currentWord = "";
currentLength = 0;
} else {
currentWord += str[i];
currentLength++;
}
}
return longestWord;
}
const inputString = "Hello world, this is a test";
const longestWord = findLongestWord(inputString);
console.log("The longest word is: " + longestWord);
该代码会输出:The longest word is: Hello
领取专属 10元无门槛券
手把手带您无忧上云