𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗿𝗼𝗴𝗿𝗮𝗺: 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗪𝗼𝗿𝗱𝘀
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.
- Set a starting point at the beginning of the string.
- Set an end point at the last character.
- Move backward through the string from the last character to the first.
- Look for a space or the start of the string.
- When you find a space, you found a word.
- Extract that word and add it to your result.
- Add a space after the word.
- Move your end point to the previous word.
- 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