Home > database >  Revers a string word by word without using inbuilt function in javascript
Revers a string word by word without using inbuilt function in javascript

Time:10-25

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....???

CodePudding user response:

Traverse the original string and reverse the individual words.

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"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are reversing the whole string. If you want to use a single function and assuming the string contains spaces only, you can loop through every character of the string.

If you encounter a space, you can append that to the result. If you encounter another character, you can prepend that to a temporary string to build a reversed version of the word.

Then append the reversed version of word to the result when the next character is either a space or when it is the last character in the iteration.

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"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related