A question that you may be asked during a programming interview is "reverse a string" or "reverse a portion of a string". The reason why you might be asked this is because the interviewer wants to see your ability to manipulate strings.
In this post, I'm going to show you how to best answer this question in both JavaScript and PHP.
If you'd rather see this post in video format, watch the video below and be sure to subscribe to my YouTube playlist Tyler Answers Interview Questions.
The best way to solve this dilemma in JavaScript is to create a reusable function that can be used to reverse strings given a specific separator.
Hey, Tyler here. I’m building Formyra, an AI-powered smart forms platform that helps businesses automate workflows, cut busywork, and turn form submissions into real growth.
If that sounds interesting, I’d love for you to check it out!
In the answer below, we've created a function called rvsBy that takes a string and a separator value. We'll use this function to first reverse our entire sentence by character, and then undo the reversed order of words by calling the function on the reversed sentence.
JavaScript
const sentence = 'This is a sentence!'
const rvsBy = (string, separator) => {
return string.split(separator).reverse().join(separator)
}
const newSentence = rvsBy(sentence, '') // !ecnetnes a si sihT
const answer = rvsBy(newSentence, ' ') // sihT si a !ecnetnes
We've now answered the interview question by keeping the order of the sentence while reversing the individual words.
In the PHP solution, we'll create the same basic function. There are some differences, however, due to how PHP allows us to manipulate strings and arrays.
Also, we'll have to perform a conditional statement to use str_split instead of explode when attempting to create a new array of individual characters.
Other than that, you'll see the function is overall the same.
PHP
$sentence = 'This is a sentence!';
function rvsBy($string, $separator) {
if ($separator === '') {
$array = str_split($string);
} else {
$array = explode($separator, $string);
}
$reversed = array_reverse($array);
return join($separator, $reversed);
}
$reversedSentence = rvsBy($sentence, ''); // !ecnetnes a si sihT
$answer = rvsBy($reversedSentence, ' '); // sihT si a !ecnetnes
Tweet me @tylerewillis