How can you reverse output a string in the C language?
There are several ways to output a string in reverse order using the C language.
- Iterate through the string using a loop and output it in reverse.
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int length = strlen(str);
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
}
int main() {
char str[] = "Hello, World!";
reverseString(str);
return 0;
}
- Reverse the string using a recursive function.
#include <stdio.h>
void reverseString(char* str) {
if (*str) {
reverseString(str + 1);
printf("%c", *str);
}
}
int main() {
char str[] = "Hello, World!";
reverseString(str);
return 0;
}
Both methods can achieve the function of reversing a string, the specific choice between the two depends on personal preference and project requirements.