👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
One of the first code / algorithm challenges we set out to tackle as budding software engineers and web developers is seeing if we can figure out how to reverse a string. Remember that a chain is just a collection of characters and spaces. What we need to do is try to reverse, for example, the string "Hello everyone !" ¬ª And back¬´! EDNOM olleH ‚". There are several ways we can fix this problem and we are going to cover some of them here in this article.
Write a function
ReverseString, which reverses a string and returns it. The string to be reversed is provided as an argument in the function.
Solution n. 1: To loop
The first and probably one of the easiest solutions is to use a loop and go back through the chain. We will need to instantiate, or create, a variable that contains the new inverted string that we pass each character in the string:
assign i to the last index (which is calculated when we take 1 of the length of the string) ‚áí this is our initialization and it will serve as the first clue that we will look at. The second part of the loop is our state ‚áí that tells the loop when to stop. The third and final part of the loop is how much our i increases after the loop is completed and the condition is still true: I- basically takes our i and reassigns it at - 1;
As we loop through each iteration, we take each str [i] character and add it to newStr. We then go back to the newStr outside of our loop and exit the function.
Try it yourself in the code editor: