题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/dfeed0e0e4624814b122265e859783b2
//sort函数对输入的字符串长度排序
#include "stdio.h"
#include "string"
#include "algorithm"
using namespace std;
struct charNode{
int length;
string str;
};
bool cmp(charNode lhs,charNode rhs){
if (lhs.length < rhs.length)
return true;
return false;
}
int main(){
int n;char buf[110];charNode array[1000];
while (scanf("%d\n",&n)!=EOF){
int i;
for (i = 0; i < n; ++i) {
fgets(buf,110,stdin);
string str = buf;str.pop_back();
if (str == "stop")
break;
array[i].str = str;
array[i].length = str.size();
}
sort(array,array+i, cmp);
for (int j = 0; j < i; ++j) {
printf("%s\n",array[j].str.c_str());
}
}
}
