Solution Review: Reverse a String
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
In the above code, there are three basic functions: reverse1, reverse2, and reverse3. Let’s study them one by one.
1st Variant
Look at the header of function reverse1 at line 5: func reverse1(s string) string. It takes a string s as a parameter to reverse it and returns the reversed string. This variant is the implementation of a slice of bytes, converting it later into a string.
At line 6, we make a slice of bytes sl, containing all the elements from string s passed to the function reverse1. Next, we make an array rev of byte type of length 100 (assuming that the length of the string s doesn’t exceed 100). At line 8, we make an iterator j that we will use to traverse through the rev array as we move forward, filling rev with values.
Then we have a for loop at line 9. You may have noticed that the iterator i of this loop is initialized with len(sl)-1. It will move in a backward direction until we reach the 0th index. This is because we have to reverse the string; the idea is to read sl in a backward direction and store each character in rev in the forward direction. That’s the reason we have a separate iterator j for rev that starts from 0. At ...