-4

Without using the split reverse and join functions, how would one do such a thing?

The Problem Given: Reverse the words in a string Sample Input: "Hello World" Sample Output: "World Hello"

<script>
  var newString = ""; 
  var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)"); 

  newString = theString.split(" ").reverse().join(" ")


  document.write(newString);
</script>

I am able to make it using the inbuilt methods. But the question asks to use only use

  • Arrays
  • Substring
  • charAt()

So how would I go about this?

Ghazanfar
  • 1,419
  • 13
  • 21
saj5211
  • 51
  • 1
  • 9

1 Answers1

-1

ok, so you are allowed to use charAt which you can use to find the spaces between words. When you know where the spaces are you can use substring to isolate the individual words and store them in variables. Then you can move them around and join them back together. So as an example:

var string = "Hello World",
    words = [],
    reversedString="",
    i;

for (i=0; i<string.length; i++) {
  if (string.charAt(i) === " ") {
    words.push(string.substring(0, i));
    words.push(string.substring(i));
  }
}

for (i=words.length-1; i>=0; i--) {
  reversedString += words[i];
}

Please note this is just a simple (untested) example and will only work for a string of two words. If you want to make it work with more you need to change the logic around the substrings. Hope it helps!

EDIT: Just noticed I didn't reverse the string at the end, code updated.

Here's a couple of references in case you need them: substring charAt

ewanc
  • 1,284
  • 1
  • 12
  • 23
  • Thanks, appreciate it – saj5211 Nov 30 '15 at 18:02
  • Sorry, that wasn't directed at you, just whoever it was. It's not helpful to downvote an answer without an explanation as to why. Can the person who downvoted please let me know why and how they feel the answer could be improved. Thanks – ewanc Nov 30 '15 at 22:55