04.四.1 使用遞迴方法編寫函式,實現將輸入字串反向儲存
阿新 • • 發佈:2020-12-16
技術標籤:C程式設計題練習
使用遞迴方法編寫函式,實現將輸入字串反向儲存
#include <stdio.h> #include<stdlib.h> #include <string.h> //使用遞迴方法編寫函式,實現將輸入字串反向儲存 void rev(char * s); int main (){ // char str[]={'h','e','l','l','o','\0'}; //可以這麼定義 char str[]="hello world"; //字元陣列陣列用字串常量進行初始化末尾會自動新增'\0' // char *str ="hello"; //不能這麼定義,初始化指標時所建立的字串常量被定義為只讀,不能修改 printf("%s\n",str); rev (str); printf("%s",str); return 0; } void rev(char * s) { char *p=s; char temp; while (*p != '\0') { p++; } p--; if (s<p) { temp=*s; *s=*p; *p='\0'; rev(s+1); *p=temp; } }