将一个字符串逆序排列

  • Post author:
  • Post category:其他




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

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




版权声明:本文为u013243314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。