C++ 按降序對字串排序
在 C++ 程式設計中,可以透過使用字串排序方法或其他方法按升序或降序進行排序。但在這裡,為了將單詞按降序排列,需要涉及到字串比較(第一個單詞與第二個單詞比較)和複製(將第一個單詞複製到一個臨時變數中)方法參與到內層和外層遍歷迴圈中,如下所示。
示例
#include<bits/stdc++.h>
using namespace std;
int main(){
char str[3][20]={"Ajay","Ramesh","Mahesh"};
char t[20];
int i, j;
for(i=1; i<3; i++){
for(j=1; j<3; j++){
if(strcmp(str[j-1], str[j])>0){
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"Sorted in Descending Order ::";
for(i=3; i>=0; i--){
cout<<" ";
cout<<str[i]<<"\n";
}
return 0;
}輸出
接收三個單詞(Ajay、Ramesh 和 Mahesh)作為輸入後,此程式按降序對字串排序,產生以下結果;
Sorted in Descending Order:: Ramesh Mahesh Ajay
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP