𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗿𝗼𝗴𝗿𝗮𝗺: 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗪𝗼𝗿𝗱𝘀

You want to reverse the order of words in a string. Most people think this is hard. It is simple if you follow a logic.

The Goal: Turn "YOU ARE HOW" into "HOW ARE YOU".

The Logic: You need to find where each word starts and ends.

  1. Set a starting point at the beginning of the string.
  2. Set an end point at the last character.
  3. Move backward through the string from the last character to the first.
  4. Look for a space or the start of the string.
  5. When you find a space, you found a word.
  6. Extract that word and add it to your result.
  7. Add a space after the word.
  8. Move your end point to the previous word.
  9. Repeat until you reach the beginning.

The Code:

let start = 0; let sen = "YOU ARE HOW"; let len = sen.length - 1; let end = len; let result = "";

for (let i = end; i >= 0; i--) { if (sen[i] == " " || i == 0) { if (i == 0) { start = i;
} else { start = i + 1; }

    for (let j = start; j <= end; j++) {
        result += sen[j];
    }
    result += " ";
    end = i - 1;
}

}

console.log(result);

This method works by identifying word boundaries. It helps you understand how to manipulate strings using loops and indices.

Source: https://dev.to/harini_magesh_fa40041cf8d/string-program-2e3g