题目如下: 写一个函数,将字符串翻转,翻转方式如下:“I am a student”反转成“student a am I”,不借助任何库函数。
方法1(自己写的) #include
- #include<stdlib.h>
- char* reserve(char* str);
- int get_length(char *str);
- int main(void)
- {
- char *str="I am a student";
- str="you are a student";
- char *result=reserve(str);
- printf("%s\n",result);
- free(result);
- result=NULL;
- str=NULL;
- return 0;
- }
- int get_length(char *str)
- {
- int length=-1;
- if(str!=NULL)
- {
- length=0;
- while(*str++!='\0')
- {
- length++;
- }
- }
- return length;
- }
- char* reserve(char* str)
- {
- int i=get_length(str);
- printf("%d\n",i);
- char* result=malloc(sizeof(char)*(i+1));
- if(result==NULL)
- {
- printf("%s\n","allocate string failed");
- exit(1);
- }
- char* temp=malloc(sizeof(char)*i);
- if(temp==NULL)
- {
- printf("%s\n","allocate string failed");
- exit(2);
- }
- char c='\0';
- int n=i-1;
- int m=0;
- c=*str;
- while(c!='\0')
- {
- if( ')
- {
- temp[m++]=c;
- }
- else
- {
- for(m=m-1;m>=0;m--)
- {
- result[n--]=temp[m];
- }
- result[n--]=c;
- m=0;
- }
- str++;
- c=*str;
- }
- for(m=m-1;m>=0;m--)
- {
- result[n--]=temp[m];
- }
- free(temp);
- temp=NULL;
- return result;
- }
方法2(从网上收集过来的)
- #include <stdio.h>
- void main()
- {
- char str[]="you are a student";
- printf(str);
- printf("\n");
- char *p,*q;
- char temp;
- p=q=str;
- while(*q!='\0')
- {
- q++;
- }
- q--;
- while(p<=q)
- {
- temp=*p;
- *p=*q;
- *q=temp;
- p++;
- q--;
- }//反转整个字符串
- printf(str);
- printf("\n");
- char *s;
- q=p=s=str;//指针指向开始位置
- while(*q!='\0')
- {
- if(*q==' '||*(q+1)=='\0')
- {
- p--;
- if(*(q+1)=='\0')//处理最后一个字串
- p++;
- while(s<=p)
- {
- temp=*p;
- *p=*s;
- *s=temp;
- s++;
- p--;
- }//反转局部字符串
- s=q+1;
- p=q;
- }
- q++;
- p++;
- }
- printf(str);
- printf("\n");
- }
方法3(传说中是《程序员面试宝典》里的方法,不过我没有看过这本书,也没去验证): #include
- #include <stdio.h>
- int main(void)
- {
- int num=-12345,j=0,i=0,flag=0,begin,end;
- char str[]="I am a student",temp;
- j=strlen(str)-1;
- printf(" string=%s\n",str);
- //第一步是进行全盘反转,将单词变成“tneduts a ma I”
- while(j>i)
- {
- temp=str[i];
- str[i]=str[j];
- str[j]=temp;
- j--;
- i++;
- }
- printf(" string=%s\n",str);
- int i=0;
- //第二步进行部分反转,如果不是空格则开始反转单词
- while(str[i])
- {
- if(str[i]!=' ')
- {
- begin=i;
- while(str[i]&&str[i]!=' ')
- {
- i++;
- }
- i=i-1;
- end=i;
- }
- while(end>begin)
- {
- temp=str[begin];
- str[begin]=str[end];
- str[end]=temp;
- end--;
- begin++;
- }
- i++;
- }
- printf(" string=%s\n",str);
- return 0;
- }
阅读(579) | 评论(1) | 转发(0) |