C语言 实现逆置功能
//凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/
1. 字符串的逆置
方法1:利用数组
1 #include<stdio.h> 2 #include<string.h> 3 void fun(char a[]){ 4 int i,len; 5 char ch; 6 len=strlen(a); 7 for(i=0;i<len/2;i++){ 8 ch=a[i]; 9 a[i]=a[len-1-i]; 10 a[len-1-i]=ch; 11 } 12 } 13 14 void main(){ 15 char s[10]; 16 printf("Pealse input a string:\n"); 17 gets(s); 18 printf("The string has been inverted:\n"); 19 fun(s); 20 puts(s); 21 }
结果为:
方法2:利用指针
1 #include<stdio.h> 2 #include<string.h> 3 void fun(char *a){ 4 if(*a){ 5 fun(a+1); 6 printf("%c",*a); 7 } 8 } 9 10 void main(){ 11 char s[10]; 12 printf("Pealse input a string:\n"); 13 gets(s); 14 printf("The string has been inverted:\n"); 15 fun(s); 16 printf("\n"); 17 }
结果为:
2.输入10个数,逆置输出
方法1:利用数组
1 #include<stdio.h> 2 #include<string.h> 3 #define N 10 4 5 #if(1) 6 void reverse(int x[],int n){ 7 int i,j,temp,m; 8 m=(n-1)/2; 9 for(i=0;i<=m;i++){ 10 j=n-1-i; 11 temp=x[i]; 12 x[i]=x[j]; 13 x[j]=temp; 14 } 15 } 16 #endif 17 18 #if(0) 19 void reverse(int *x,int n){ 20 int *i,*j,*p,temp,m; 21 m=(n-1)/2; 22 i=x; //i->x[0] 23 j=x+n-1; //j->x[n-1] 24 p=x+m; //p->x[m] 25 for(;i<=p;i++,j--){ 26 temp=*i; 27 *i=*j; 28 *j=temp; 29 } 30 } 31 #endif 32 33 void main(){ 34 int i,a[N]; 35 printf("Pealse input %d numbers:\n",N); 36 for(i=0;i<N;i++){ 37 scanf("%d",a+i); 38 } 39 reverse(a,N); 40 printf("The array has been inverted:\n"); 41 for(i=0;i<N;i++){ 42 printf("%2d",a[i]); 43 } 44 printf("\n"); 45 }
结果为:
方法2:利用指针
1 #include<stdio.h> 2 #include<string.h> 3 #define N 10 4 5 #if(0) 6 void reverse(int x[],int n){ 7 int i,j,temp,m; 8 m=(n-1)/2; 9 for(i=0;i<=m;i++){ 10 j=n-1-i; 11 temp=x[i]; 12 x[i]=x[j]; 13 x[j]=temp; 14 } 15 } 16 #endif 17 18 #if(1) 19 void reverse(int *x,int n){ 20 int *i,*j,*p,temp,m; 21 m=(n-1)/2; 22 i=x; //i->x[0] 23 j=x+n-1; //j->x[n-1] 24 p=x+m; //p->x[m] 25 for(;i<=p;i++,j--){ 26 temp=*i; 27 *i=*j; 28 *j=temp; 29 } 30 } 31 #endif 32 33 void main(){ 34 int i,a[N]; 35 printf("Pealse input %d numbers:\n",N); 36 for(i=0;i<N;i++){ 37 scanf("%d",a+i); 38 } 39 reverse(a,N); 40 printf("The array has been inverted:\n"); 41 for(i=0;i<N;i++){ 42 printf("%2d",a[i]); 43 } 44 printf("\n"); 45 }
结果为: