在对字符串的排序中,往往具有不同的规则来判断字符串的大小先后。这里有两种比较常见的规则:

1个回答

  • #include

    #include

    using namespace std;void main(){ ifstreaminfile("D:\Input.txt" , ios::in ); ofstream outfile("D:\Output.txt", ios::out); if (infile) { int No = 0; infile >> No; char *p[100]; for (int i = 0; i < No; i++) { p[i] = new char; infile >> p[i]; } for (int i = 0; i < No; i++) { for (int j = i + 1; j < No; j++) { if (strlen(p[j]) < strlen(p[i])) { //后者长度小于前者就交换 char *p1 = p[i]; p[i]= p[j]; p[j]= p1; } else if (strlen(p[j]) == strlen(p[i])) { //后者长度等于前者就比较 if (strcmp(p[i], p[j]) > 0) { char *p2 = p[i]; p[i]= p[j]; p[j]= p2; } } } outfile << p[i] << "t"; } outfile << endl; for (int i = 0; i < No; i++) { for (int j = i + 1; j < No; j++) { if (strcmp(p[i], p[j]) > 0) { char *p3 = p[i]; p[i]= p[j]; p[j]= p3; } } outfile << p[i] << "t"; } outfile << endl; } else { outfile << "测试文件Input.txt不存在!!!" << endl; } infile.close() ; outfile.close();}运行结果: