How to output the reverse string in C language?

One option is to use a loop and a decreasing index to output the reversed string. Here are the specific steps:

  1. Create a character array to store the string to be output.
  2. Using a loop, start from the last character of the string and decrease the index until it reaches 0.
  3. Iterate through the character array and output each character one by one.

Here is an example code:

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    printf("请输入一个字符串:");
    scanf("%s", str);

    int length = strlen(str);
    printf("相反字符串为:");
    for (int i = length - 1; i >= 0; i--) {
        printf("%c", str[i]);
    }
    printf("\n");

    return 0;
}

After running the program, input a string and the program will output the reverse of that string.

bannerAds