将一个字符串逆序排列

来源:互联网 发布:mac玩英雄联盟怎样散热 编辑:程序博客网 时间:2024/05/16 19:44


将一个字符串逆序排列:原地转换

#include <stdio.h>
int count(char * s)
{
     int n = 0;
     while(*s++ != '\0')
     n++;

     printf("n = %d\n",n);
     return n;
}

void conver(char * s,int n)
{
     int i,j;
 for(i = 0; i < n;i++,n--)
 {
      if(i != n)
     {
         j = s[i];
         s[i] = s[n-1];//减一的原因是:数组下标从0开始
         s[n-1] = j;
     }
 }

}


void main()
{
    int i;
    char shuzu[] = "welcome to!";

    printf("strlen(shuzu) = %d\n",strlen(shuzu));
    printf("sizeof(shuzu) = %d\n",sizeof(shuzu));//比较下strlen和sizeof区别
    i = count(shuzu);
    conver(shuzu,i);
    printf("after the conver,the string is:%s\n",shuzu);
 
}

另一种转换方法:指针

#include <stdio.h>
char* reverse(char* s)
{
     char*  t; 头
     char* w;尾
     t = s;
     w = s;
    while(*w++ != '\0'); 这和while(*w++)一样  //while(*w != '\0') 两种方法,自己体会
    w--;                                                               // w++; 
    w--;                                                              // w--;
 while(w>t)
 {
     int temp;
     temp = *t;
    *t++ = *w;
    *w-- = temp;
 }
   return s;


}


void main()
{
    char str[]="hello!";
    reverse(str);
    printf("after the reverse,the string is : %s\n",str);

}


将一句字符逆序:
#include <stdio.h>
void exchange(char* t,char* w)
{
     while(w>t)
    {
        int temp;
        temp = *t;
        *t++ = *w;
        *w-- = temp;
    }
}
void reverse(char* s)
{
     char* p;
     char* q;
     p = s;
     q = s;
    while(*q != '\0')
    {
        if(*q == ' ')
       {
           exchange(p,q-1);
           q++;
           p=q;
      }
      else
           q++;
 }
      exchange(p,q-1);
      exchange(s,q-1);
}
void main()
{
     char str[] = "welcome to china !";
     reverse(str);
     printf("the string is %s\n",str);
}

0 0
原创粉丝点击