如何实现逆序打印

方法一:先求出字符串长度,然后反向遍历。

代码如下:

#include "stdafx.h"
#include <string.h>
void ReversePrint(const char* s)
{
    int len = strlen(s);
    for (int i = len - 1; i >= 0; i--)
        printf("%c", s[i]);    
}
int main()
{
    char a[] = "abcd";
    ReversePrint(a);
    printf("
");
    getchar();
    return 0;
}

    效果如图:

    方法二:先遍历到末尾,然后再遍历回来。

代码如下:

#include "stdafx.h"
#include <stdio.h>
void ReversePrint(const char* s)
{
    const char* p = s;
    while (*p) p++;
    p--;
    while (p >= s)
    {
        printf("%c", *p);
        p--;
    }
}
int main()
{
    char a[] = "abcd";
    ReversePrint(a);
    printf("
");
    getchar();
    return 0;
}

方法三:递归遍历。

代码如下:

#include "stdafx.h"
#include <stdio.h>
void ReversePrint(const char* s)
{
    if (*(s + 1) != '')
        ReversePrint(s + 1);
    printf("%c", *s);
}
int main()
{
    char a[] = "abcd";
    ReversePrint(a);
    getchar();
    return 0;
}

    效果如图:

原文地址:https://www.cnblogs.com/cysolo/p/3621168.html