//寫一個函數,将字元串翻轉,翻轉方式如下:“I am a student”反轉成“student a am I”,不借助任何庫函數。
方法是先反轉整個字元串,然後再反轉字串。譬如先将“I am a student”反轉為“tneduts a ma I”,然後再對每個字串(空格分割)反轉一次。
算法
1 #include <stdio.h>
2
3 void main()
4 {
5 char str[]="I am a student";
7 printf(str);
8 printf("\n");
9
10 char *p,*q;
11 char temp;
12 p=q=str;14 while(*q!='\0')
15 {
16 q++;
17 }
18 q--;
19 while(p<=q)
20 {
21 temp=*p;
22 *p=*q;
23 *q=temp;
24 p++;
25 q--;
26 }//反轉整個字元串
27
28 printf(str);
29 printf("\n");
30
31 q=str;//指針指向開始位置
32 char *s,*t;
33 s=t=str;
34 while(*q!='\0')
35 {
36 if(*q==' ')
37 {
38 t--;
39 while(s<=t)
40 {
41 temp=*t;
42 *t=*s;
43 *s=temp;
44 s++;
45 t--;
46 }//反轉局部字元串
47
48 s=q+1;
49 t=q;
50 }52 q++;
53 t++;
54 }
55
56 printf(str);
57 printf("\n");
58 }
改進
運作之後,我發現是成功的。
但是怎麼想都感覺有點問題,把“I am a student”換成“you are a student”果然有問題。
沒有處理最後一個字串的緣故。因為我是按照
if(*q==' ')
來處理字串的,而字元串最後一個的結尾沒有空格了,而是以'\0'結尾的。
最後一個字串的處理我是這樣做的。
if(*q==' '||*(q+1)=='\0')
{
t--;
if(*(q+1)=='\0')//處理最後一個字串
t++;
看上去有點奇怪吧,但是确實是可以了。
代碼貌似可以繼續優化吧。怎麼都感覺自己寫的代碼好爛。
代碼
以下是完整代碼
#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");
}
另外給一個我在《程式員面試寶典》看到的代碼,不過這個主要采用數組處理,而且使用了庫函數(strlen()),但是思想差不多吧。可以參考參考。
《程式員面試寶典》實作方法
#include <iostram>
#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;
}
既然看到了,就應該要思考吧。僅提升..