将一个字符串逆序排列



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

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值