C++_字串排序
阿新 • • 發佈:2018-12-15
偽碼:
ORDER(str1,str2,str3) //字串排序//
- output("please input three strings\n")
- input(str1,str2,str3) //輸入字串//
- if( strcmp (str1,str2)>0)
- then swap(str1,str2)
- if( strcmp (str1,str3)>0)
- then swap(str1,str3)
- if( strcmp (str2,str3)>0)
- then swap(str2,str3); //
- output ("after being sorted",str1,str2,str3)
swap(p1,p2) //交換資料//
- strcpy(p,p1)
- strcpy(p1,p2)
- strcpy(p2,p)
測試用例:
please input three strings
dhjka
fdsjifjl
oifdjk
測試結果:
after being sorted
dhjka
fdsjifjl
oifdjk
源程式:
#include"iostream" using namespace std; int main() { char str1[20],str2[20],str3[20],p[20]; printf("please input three strings\n"); cin>>str1; cin>>str2; cin>>str3; if(strcmp(str1,str2)>0) { for(int i=0;i<20;i++) { p[i]=str1[i]; str1[i]=str2[i]; str2[i]=p[i]; } } if(strcmp(str1,str3)>0) { for(int i=0;i<20;i++) { p[i]=str1[i]; str1[i]=str3[i]; str3[i]=p[i]; } } if(strcmp(str2,str3)>0) { for(int i=0;i<20;i++) { p[i]=str2[i]; str2[i]=str3[i]; str3[i]=p[i]; } } printf("after being sorted\n"); printf("%s\n%s\n%s\n",str1,str2,str3); system("pause"); return 0; }