1. 程式人生 > >c++字符串排序

c++字符串排序

技術 inpu out ostream har ace sin 技術分享 cmp

11:在主函數中輸入10個等長的字符串,用另一函數對它們排序。然後在主函數輸出這10個已排好序的字符串。

用兩種方法完成。

方法一:用二維數組做函數參數;

方法二:用指向一維數組的指針做函數參數。

方法一:二維數組:

#include<iostream>

#include<string.h>

using namespace std;

int main()

{

char str[10][20];

cout<<"input 10 strings in the same length:"<<endl;

for(int i=0;i<10;i++)cin>>str[i];

void sort(char [10][20]);

sort(str);

cout<<"now the sorted strings are:"<<endl;

void print(char [10][20]);

print(str);

return 0;

}

void sort(char a[10][20])

{

for(int i=0;i<10;i++)

{int k=i;char t[20];

for(int j=i;j<10;j++)

if(strcmp(a[j],a[k])<0)

{

strcpy(t,a[j]);strcpy(a[j],a[k]);strcpy(a[k],t);

}

}

}

void print(char a[10][20])

{

for(int j=0;j<10;j++)cout<<a[j]<<endl;

}

運行結果:

技術分享

方法二:用指向一維數組的指針做函數參數

#include<iostream>

#include<string.h>

using namespace std;

int main()

{

char (*p)[10];char ch[10][10];

cout<<"input 10 strings:"<<endl;

for(int i=0;i<10;i++)cin>>ch[i];

p=ch;

void sort(char (*)[10]);

sort(p);

cout<<"now the strings are:"<<endl;

for(int j=0;j<10;j++)cout<<p[j]<<endl;

return 0;

}

void sort(char (*p)[10])

{

for(int i=0;i<10;i++)

{int k=i;char t[10];

for(int j=i;j<10;j++)

if(strcmp(p[j],p[k])<0)

{

strcpy(t,p[j]);strcpy(p[j],p[k]);strcpy(p[k],t);

}

}

}

運行結果:

技術分享

c++字符串排序