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