编写字符串反转函数 .
首先用數組下標的形式實現:
提供三種方法:
??? 1、有中間變量
??? 2、無中間變量
??? 3、堆棧實現
?? #include <stdio.h>
??? #include <string.h>
??? void reverse_str(char * ch);
??? void reverse_str2(char *ch);
??? int main(void)
??? {
?????? char c[] = "Can you reverse me?";
?????? printf("original string c: /n%s/n", c);
?????? reverse_str(c);
?????? printf("reversed string after calling reverse_str: /n%s/n", c);
?????? reverse_str2(c);
?????? printf("reversed string after calling reverse_str2: /n%s/n", c);
?????? system("pause");
?????? return 0;
??? }
??? void reverse_str(char *ch)? /*使用中間變量*/
??? {
?????? int len;
?????? int i;
?????? len = strlen(ch)-1;
?????? char ctemp;
?????? for(i = 0; i < len-i; i++)
?????? {
???????????? ctemp = ch[i];
???????????? ch[i] = ch[len-i];
???????????? ch[len-i] = ctemp;
?????? }
?????? ch[len+1] = 0;
??? }
-------------------------------------------------------
??? void reverse_str2(char *ch)?? /*不用中間變量*/
??? {
?????? int len;
?????? int i;
?????? len = strlen(ch)-1;
?????? char ctemp;
?????? for(i = 0; i < len-i; i++)
?????? {
???????????? ch[i] = ch[i] ^ ch[len-i];
???????????? ch[len-i] = ch[i] ^ ch[len-i];
???????????? ch[i] = ch[i] ^ ch[len-i];
?????? }
?????? ch[len+1] = 0;
??? }
---------------------------------------------------------
?
//堆棧實現
我沒有記錯的話是一道MSN的筆試題,網上無意中看到的,拿來做了一下。題目是這樣的,給定一個字符串,一個這個字符串的子串,將第一個字符串反轉,但保留子串的順序不變。例如:
輸入: 第一個字符串: "This is zhuxinquan's Chinese site: http://www.zhuxinquan.com/cn"
子串: "zhuxinquan"
輸出: "nc/moc.zhuxinquan.www//:ptth :etis esenihC s'zhuxinquan si sihT"
一般的方法是先掃描一邊第一個字符串,然后用stack把它反轉,同時記錄下子串出現的位置。然后再掃描一遍把記錄下來的子串再用stack反轉。我用的方法是用一遍掃描數組的方法。掃描中如果發現子串,就將子串倒過來壓入堆棧。
最后再將堆棧里的字符彈出,這樣子串又恢復了原來的順序。源代碼如下:
總結
以上是生活随笔為你收集整理的编写字符串反转函数 .的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: open-fopen read-frea
- 下一篇: 编写字符串比较函数strcmp .