Two Three possible implementations: one only prints the string in reverse. Another reverses the string in-memory and in-place. Both assume that defining your own recursive functions is allowed and that parameters don't count as variables. In any case, the parameters themselves are const
ant, so arguably not variables.
void printRev(const char * const s){
if(*s != '\0'){ // or just: if(*s){
printRev(s + 1);
putchar(*s);
}
}
Does 'prefix' recursion through the string: first recurse until the end is reached, then print each character after the recursive call returns.
void revStr(char * const s, const int len){
if(len > 0){
if(s[0] != s[len]){
s[0] ^= s[len];
s[len] ^= s[0];
s[0] ^= s[len];
}
revStr(s + 1, len - 2);
}
}
Is slightly more involved: it XOR-swaps the 'first' character of the string with the 'last'. Then recurses with the next character as the start of the string, and the length decreased by two. So in the next iteration the second character becomes the first, and the second to last becomes the last character. For this the s
pointer itself is still const
, but obviously the characters pointed to are modified.
The second function requires the string length as an input parameter, this can also be done (recursively) without needing the built-in strlen
function:
int myStrlen(const char * const s){
if(*s != '\0'){
return 1 + myStrlen(s + 1);
}
return 0;
}
Addit
Here is a version that does not use a length parameter, but requires a disjoint output string, and the input string to be modifiable. It simulates the len - 2
expression from revStr
by replacing the last character in src
with a NUL-character.
void copyRev(char * const restrict dst, char * const restrict src){
if(src[0] != '\0'){
dst[0] = src[myStrlen(src) - 1];
dst[myStrlen(src) - 1] = src[0];
src[myStrlen(src) - 1] = '\0';
copyRev(dst + 1, src + 1);
}
}