翻轉字符串i am a student

翻轉字符串 i am a student 爲student a am i
我們可以先把字符串通過指針整體翻轉爲tneduts a am i, 然後在依次局部進行轉換
#include <stdio.h>
  int  main()
  {
    char str[]="I am a student"; 
	printf("%s\n",str);
    char *l,*r;
    char temp;
     l=r=str;
	 while(*r!='\0')
     {
         r++;//右指針後移
     }
     r--;
     while(l<=r)
     {
        temp=*l;
        *l=*r;
         *r=temp;
         l++;
         r--;
     }//反轉整個字符串爲 tneduts a am i
 
    printf("%s\n",str);
    //反轉局部字符串
     r=str;//指針指向開始位置
     char *s,*t;
     s=t=str;//這裏的字符串爲tneduts a am i
 
     while(*r!='\0')
     {
         if(*r==' ')//通過判斷空格來翻轉字符串
         {
             t--;
             while(s<=t)
             {
                temp=*t;
                 *t=*s;
                *s=temp;
                 s++;
                 t--;
             }
 
             s=r+1;
             t=r;
         }        
		 r++;
         t++;
    }
 printf("%s\n",str);
 return 0;
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章