Example 1: Reverse a String Using for Loop
Output
Enter a string: hello world dlrow olleh
In the above program, the user is prompted to enter a string. That string is passed to the reverseString() function.
Inside the reverseString() function,
- An empty newString variable is created.
- The
forloop is used to iterate over the strings. During the first iteration,str.length - 1gives the position of the last element. That element is added to the newString variable.
This process continues for all the string elements. - The value of i decreases in each iteration and continues until it becomes 0.
Example 2: Reverse a String Using built-in Methods
Output
Enter a string: hello olleh
In the above program, the built-in methods are used to reverse a string.
- First, the string is split into individual array elements using the
split()method.str.split("")gives ["h", "e", "l", "l", "o"]. - The string elements are reversed using the
reverse()method.arrayStrings.reverse()gives ["o", "l", "l", "e", "h"]. - The reversed string elements are joined into a single string using the
join()method.reverseArray.join("")gives olleh.