字符串逆序

来源:互联网 发布:c语言包含哪些课程 编辑:程序博客网 时间:2024/06/07 19:07

/*----------方法1--------------*/

#include <stdio.h>
#include <stdlib.h>

invert_str(char *s)
{
 char *p,*q;
 int i=0;
 while(*s!='/0')
 {
  s++;
  i++;
 }
    s--;
 while(i>0)
 {
  printf("%c",*(s--));
  i--;
 }
}

main()
{
 char *str = "123456789";
    invert_str(str);
 printf("/n");
}

 

/*--------------方法2-----------------*/

#include <stdio.h>
#include <stdlib.h>

char* invert_str(char *s)
{
 char *p,*q;
 int i=0;
 p=(char*)malloc(strlen(s)*sizeof(char));
 q=p;
 while(*s!='/0')
 {
  s++;
  i++;
 }
    s--;
 while(i>0)
 {
  *p++=*s--;
  i--;
 }
 *p='/0';
 return q;
}

main()
{
 char *str = "123456789";
    char *s = invert_str(str);
 printf("%s/n",s);
}

 

/*----------方法3 递归实现(这个是别人写的)----------------*/

void revers()
{
    char c;
    if((c = getchar()) != '/n') //关于这里我不是很明白,为什么这样就可以逆序输出呢?
        revers();
    if(c != '/n')
        putchar(c);
}

void main()
{
    revers();
    printf("/n");
}

 

/*---------------方法4 使用顺序栈来实现------------------*/

#include <stdio.h>
#include <stdlib.h>

main()
{
 int a[10];
 int top = 0;
 int i=0;
 char c;
 while((c=getchar())!='/n')
 {
  a[top]=c;
  top++;
 }
 
 while(top>0)
 {
  printf("%c",a[--top]);
 }
}