logo CodeStepByStep logo

reverse_chunks

Language/Type: PHP string return

Write a function named reverse_chunks that accepts a string s and integer k as parameters and returns a new string that reverses the relative order of every k characters of s. For example, the call of reverse_chunks("MehranSahami", 3) should view the string in groups of 3 characters at a time, reversing "Meh" into "heM", and "ran" into "nar", and so on, returning a result of "heMnarhaSima".

If the string's length is not an exact multiple of k, the last chunk of fewer-than-k characters at the end of the string should be left in its original order. For example, if the call is reverse_chunks("MartyStepp", 4), the first chunk "Mart" becomes "traM" and the second chunk "ySte" becomes "etSy". The last two characters, "pp", are fewer than 4, so they are left as-is. So the result returned should be "traMetSypp".

You may assume that the value passed for k will be a positive integer.

Constraints:

  • Do not use any data structures such as arrays to help you solve this problem.
  • You may declare as many simple variables like Integer, String, etc. as you like.

Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.