Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Created March 24, 2017 03:14
Show Gist options
  • Save jmsevold/38151720f0a2b10793d0cd6c1c616e22 to your computer and use it in GitHub Desktop.
Save jmsevold/38151720f0a2b10793d0cd6c1c616e22 to your computer and use it in GitHub Desktop.
reverse words in a sentence
let sentence = "Hello World";
function replaceChar(str,targetIndex,newChar){
return str.substr(0,targetIndex) + newChar + str.substr(targetIndex + 1)
}
function stringReverser(str, startIndex, endIndex) {
if (!str || str.length < 2) {
return;
}
while (startIndex < endIndex) {
let tempLeft = str[startIndex];
str = replaceChar(str, startIndex, str[endIndex]);
str = replaceChar(str, endIndex, tempLeft);
startIndex++;
endIndex--;
}
return str;
}
function reverseWords(sentence) {
// reverse the sentence
let str_len = sentence.length;
sentence = stringReverser(sentence, 0, str_len - 1);
// beginning of our strategy to idenify words
let start = 0;
let end = 0;
while (start < sentence.length) {
while (sentence[start] === ' ') {
start++;
}
end = start + 1;
while (end < sentence.length && sentence[end] != ' ') {
end++;
}
// having found the beginning and end of a word, we reverse it in place
sentence = stringReverser(sentence, start, end - 1);
start = end;
}
return sentence;
}
let result = reverseWords(sentence)
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment