本文主要是介绍将一个字符串逆序排列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
将一个字符串逆序排列:原地转换
#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);
}
void exchange(char* t,char* w)
{
while(w>t)
{
int temp;
temp = *t;
*t++ = *w;
*w-- = temp;
}
}
{
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);
}
{
char str[] = "welcome to china !";
reverse(str);
printf("the string is %s\n",str);
这篇关于将一个字符串逆序排列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!