Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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....???

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda