1. 程式人生 > >C++_字串排序

C++_字串排序

偽碼:

                      ORDER(str1,str2,str3)         //字串排序//

  1. output("please input three strings\n")
  2. input(str1,str2,str3)                              //輸入字串//
  3. if( strcmp (str1,str2)>0)
  4. then swap(str1,str2)
  5. if( strcmp (str1,str3)>0)
  6. then swap(str1,str3)
  7. if( strcmp (str2,str3)>0)
  8. then swap(str2,str3);                            //
    比較排序字串//
  9. output ("after being sorted",str1,str2,str3)

swap(p1,p2)                  //交換資料//

  1. strcpy(p,p1)
  2. strcpy(p1,p2)
  3. 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;

}