String reversal is primarily concerned with changing the index position of a string in either ascending or descending pattern. i.e. going from come to emoc. In this short tutorial, we will be looking at various ways to handle this programming task.
Task: Reverse the given string: Hello
Note: This task could be solved in numerous ways, but we will take a look at two methods on how to go about this. There are;
- Imperative approach
- Declarative approach (A single line of code does the work)
Imperative approach
Pseudocode:
We will be defining a function (just to make our code organized at this point)
- Define a function and give it a name
- The function will accept a single parameter (which is the input to the function)
- Declare a variable and initialize it with the length of the function parameter
- Declare a variable which accepts an empty string which will be used to stored our new reversed string
- Iterate through the given string from the last index in the string array.
- Return the the concatenated reversed string
- Call the function with an argument
Solution:
function reverseThisString(inputString) {
let stringLength = inputString.length
let reversedString = '';
for (let i = stringLength - 1; i >= 0; i--) {
reversedString += inputString[i];
}
return reversedString;
}
console.log(reverseThisString("hello"));
Output: olleh
Note: how the for loop here works
(let i = stringLength - 1)
: we define a variable i with a starting value of stringLength - 1 (i.e 5 - 1 = 4)
where index 4 represents the last index position o
of the sample string (Hello).
(i >= 0)
: We tell it that i
will always be greater than or equal to 0
(when it is less than 0, it should stop looping)
(i--)
: will continually decrement the loop at each iteration
Inside the for loop:
(reversedString += inputString[i];)
: At each iteration (as the condition above remains valid) store the value of the index position in the reversedString
variable.
Declarative approach
Pseudocode:
This pattern will only take a single line of code.
Use step 1,2, 6 & 7 above
- use split method with a quotation marks
split('')
to divide the strings by character i.e.'h','e','l','l','o'
- use reverse method with no quotation marks
reverse()
to iterate through the indexes of the splitted string thus reversing its position. i.e.'o','l','l','e','h'
- use join method with quotation marks
join('')
to concatenate the reversed string back with-out spaces i.e.olleh
Solution:
function reverseThisString(inputString) {
return inputString.split('').reverse().join('');
}
console.log(reverseThisString("olleh"));
console.log(reverseThisString("fantastic"));
Output: hello
Output: citsatnaf
Top comments (0)