The only way we can manipulate character strings using functions (at
least for now) is by modifying the argument that is passed in. This
means we have to reverse our string in place. We will first need to
calculate the length of the string s. We do this by
declaring the integer variable len and using a
for
-loop that increments len until
s[len]
is equal to \0
. We then decrement
len to exclude \0
.
/* reverse: reverse character string s */
void reverse(char s[])
{
int len;
for (len = 0; s[len] != '\0'; ++len)
;
--len; /* exclude \0 */
}
To reverse the string, we swap the first and the
lenth element, the second and the
len-1
th element, and so on, until i
reaches len-i
. We can achieve this using a
for
-loop that decrements len and increments
i after every swap. We swap the elements as follows, where
x and y are the elements we want to swap, and
temp is a variable we declare to store the x's
value:
temp = x;
x = y;
y = temp;
Putting it all together, our reverse
function looks like
this:
/* reverse: reverse character string s */
void reverse(char s[])
{
int len;
int i, len, temp;
for (len = 0; s[len] != '\0'; ++len)
;
--len; /* exclude \0 */
for (i = 0; i < len; ++i) {
temp = s[i];
s[i] = s[len];
s[len] = temp;
--len;
}
}