在 javascript 中不使用内置函数逐字反转字符串

Revers a string word by word without using inbuilt function in javascript

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 siht ekil I

but expected output: I ekil siht margorp yrev hcum

please can any one answer this....???

遍历原字符串,将单个单词反转

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"));

你正在反转整个字符串。如果要使用单个函数并假设字符串仅包含 spaces,则可以遍历字符串的每个字符。

如果您遇到 space,您可以将其附加到结果中。如果您遇到另一个字符,您可以将其添加到一个临时字符串中以构建该单词的反向版本。

然后,当下一个字符是 space 或迭代中的最后一个字符时,将单词的反转版本附加到结果中。

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"));