function reverse1(str) {
let r = "";
for (let i = str.length - 1; i >= 0; i--) {
r += str[i];
}
return r;
}
console.log(reverse1("I like this program very much"));
output://hcum yrev margorp sight ekill I
但预期输出:I ekill sight margorp yrev
谁能回答这个问题....??
您正在反转整个字符串。如果你想使用单个函数,并且假设字符串只包含空格,你可以遍历字符串的每个字符。
如果遇到空格,可以将其附加到结果后面。如果遇到另一个字符,可以将其添加到临时字符串中,以构建该单词的反向版本。
当下一个字符是空格或者是迭代中的最后一个字符时,将word的反转版本附加到结果中。
function reverse1(str) {
let result = "", tmp = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') {
result += ' '; continue;
}
tmp = str[i] + tmp;
if (str[i + 1] === undefined || str[i + 1] === ' ') {
result += tmp; tmp = "";
}
}
return result;
}
console.log(reverse1("I like this program very much"));
console.log(reverse1(" I like this program very much "));
console.log(reverse1("abc"));
遍历原始字符串并反转单个单词
function reverseUtil(str) {
let r = "";
for (let i = str.length - 1; i >=0; i--) {
r += str[i];
}
return r;
}
function reverse1(str) {
let r = "", tmp = "";
for (let i = 0; i < str.length; i++) {
if (str[i] == ' ') {
r += reverseUtil(tmp) + ' ';
tmp = "";
} else tmp += str[i];
}
// last word
r += reverseUtil(tmp);
return r;
}
console.log(reverse1("I like this program very much"));