首页 > 试题广场 >

字符串排序

[编程题]字符串排序
  • 热度指数:10274 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
先输入你要输入的字符串的个数。然后换行输入该组字符串。每个字符串以回车结束,每个字符串少于一百个字符。 如果在输入过程中输入的一个字符串为“stop”,也结束输入。 然后将这输入的该组字符串按每个字符串的长度,由小到大排序,按排序结果输出字符串。

输入描述:
字符串的个数,以及该组字符串。每个字符串以‘\n’结束。如果输入字符串为“stop”,也结束输入.


输出描述:
可能有多组测试数据,对于每组数据,
将输入的所有字符串按长度由小到大排序输出(如果有“stop”,不输出“stop”)。

根据输入的字符串个数来动态分配存储空间(采用new()函数)。每个字符串会少于100个字符。
测试数据有多组,注意使用while()循环输入。
示例1

输入

5
sky is grey
cold
very cold
stop
3
it is good enough to be proud of
good
it is quite good

输出

cold
very cold
sky is grey
good
it is quite good
it is good enough to be proud of

python解法:

while True:
    try:
        a, res = int(input()), []
        for i in range(a):
            string=input()
            if string!="stop":
                res.append(string)
            else:
                break
        for i in sorted(res,key=len):
            print(i)
    except:
        break
发表于 2017-10-06 15:47:36 回复(1)
Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        scanner.nextLine();
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            String line = scanner.nextLine();
            if (line.equals("stop")) break;
            else list.add(line);
        }
        list.sort(Comparator.comparingInt(String::length));
        for (String s : list) System.out.println(s);
    }
}


发表于 2020-03-20 10:11:54 回复(0)
#include <stdio.h>
#include <string.h>

typedef struct node
{
    char a[100];
}Node;
int cmp(Node *i,Node *j)
{
    return strlen((*i).a)-strlen((*j).a);
}
int main()
{
    int n,k;
    while(scanf("%d",&n)!=EOF)
    {
        getchar();                    //scanf()用%c,%s空格键,Tab键,回车键结束一次输入,不会舍弃最后的回车符或空格或Tab(即还在缓冲区中),可使用getchar来吸收scanf()执行之后的换行符。
        Node c[n];
        for(k=0;k<n;k++)
        {
            gets(c[k].a);
            if(strcmp(c[k].a,"stop")==0)break;
        }
        qsort(c,k,sizeof(Node),cmp);
        for(int i=0;i<k;i++)puts(c[i].a);
    }
}

发表于 2020-02-11 11:45:09 回复(0)
# include<stdio.h>
# include<string.h>
# include<algorithm>
using namespace std;

struct E
{
    char s[105];
    int length;
};

bool cmp(E a,E b)
{
    return a.length<b.length;
}

int main()
{
    int n,i;
    char stop[]="stop";
    while(scanf("%d",&n)!=EOF)
    {
        getchar();
        E *buf = new E[n];
        for(i=0;i<n;i++)
        {
            gets(buf[i].s);
            int tmp = strcmp(stop,buf[i].s);
            if(tmp==0)  n=i;
            buf[i].length=strlen(buf[i].s);
        }
        sort(buf,buf+n,cmp);
        for(i=0;i<n;i++)
        {
            puts(buf[i].s);
        }
    }
    return 0;
}

发表于 2018-02-16 12:20:47 回复(0)
自定义排序函数
#include <stdio.h>
#include <string.h>

typedef struct str{
    char s[100];
    int len;
}str;

int cmp(const void *a,const void *b){
        return (*(str *)a).len- (*(str *)b).len;
}

int main(){
    int n,i,j;
    while(scanf("%d ",&n)!=EOF){
        str a[n];
        for (i=0,j=0;i<n;i++) {
            gets(a[i].s);
            if(!strcmp(a[i].s,"stop")) break;            
            j++;
            a[i].len=strlen(a[i].s);
        }
        qsort(a,j,sizeof(a[0]),cmp);
        for(i=0;i<j;i++){
            printf("%s\n",a[i].s);
        }
    }
}
(•̀ᴗ•́)و

发表于 2021-03-10 22:23:48 回复(1)
#include<stdio.h>
(737)#include<string.h>
int main()
{
    int n=100,i,j;char a[100][100],b[100];
    while(scanf("%d",&n)!=EOF)
    {
        getchar();//吸收gets前面的回车
        for(i=0;i<n;i++)//1.输入
        {
            gets(a[i]);
            if(strcmp(a[i],"stop")==0)
            {
                n=i;break;//去掉stop
            }
        }
        for(i=0;i<n-1;i++)//2.冒泡排序
            for(j=0;j<n-1-i;j++)
                if(strlen(a[j])>strlen(a[j+1]))
                {//交换
                    strcpy(b,a[j]);strcpy(a[j],a[j+1]);strcpy(a[j+1],b);
                }
        for(i=0;i<n;i++) //3.输出
            printf("%s\n",a[i]);
    }
}

发表于 2020-04-06 21:26:48 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main(){
	int n;
	map<int,string>m;
	cin>>n;
	cin.ignore(1024,'\n');
	string *str=new string[n];
	for(int i=0;i<n;i++){
		
		getline(cin,str[i]);
	//	cin.ignore(1024,'\n');
		if(str[i]=="stop"){
			break;
		}
		//cout<<str[i].size()<<endl;
		m[str[i].size()]=str[i];
	}
	for(auto it=m.begin();it!=m.end();it++){
		cout<<it->second<<endl;
	}
	delete[] str;
	return 0;
}

发表于 2020-03-17 15:35:43 回复(2)
string + 冒泡排序
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    int n;
    while(scanf("%d", &n)!=EOF)
    {
        getchar();
        string ans[1001];
        int k;
        for(int i=0; i<n; i++)
        {
            getline(cin, ans[k]);
            if(ans[k]=="stop")
                break;
            k++;
        }
        for(int i=0; i<k; i++)
            for(int j=0; j<k-i-1; j++)
            {
                if(ans[j].size() > ans[j+1].size())
                {
                    string temp;
                    temp = ans[j];
                    ans[j] = ans[j+1];
                    ans[j+1] = temp;
                }
            }
        for(int i=0; i<k; i++)
        {
            cout<<ans[i]<<endl;
        }
    }
}
发表于 2019-03-23 15:05:11 回复(1)

人生苦短~

while True:
    try:
        num = int(input())
        tempInput = []
        for i in range(num):
            temp = input()
            if temp == 'stop':
                break
            tempInput.append(temp)
        tempInput.sort(key=lambda x:len(x))
        for i in tempInput:
            print(i)
    except Exception:
        break
编辑于 2018-09-29 20:51:50 回复(0)
不难,不过要细心
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define LEN 101
#define N 1000
using namespace std;

typedef struct{
    char str[LEN];
}STR;

bool cmp(STR a, STR b)
{
    return strlen(a.str)<strlen(b.str);
}

int main()
{
    int num;//记录究竟输入了几个字符串
    int n;//本打算输入几个字符串
    STR a[N];
    while(scanf("%d", &n)!=EOF)
    {
        num=0;
        getchar();//吸收回车
        for(int i=0; i<n; i++)
        {
            gets(a[num++].str);
            if(strcmp(a[num-1].str, "stop")==0)
            {
                num--;
                break;
            }
        }
        sort(a, a+num, cmp);
        for(int i=0; i<num; i++)
        {
            puts(a[i].str);
        }
    }
    return 0;
}

编辑于 2018-02-22 17:28:49 回复(0)
try:
    while 1:
        n = input()
        result = []
        for i in xrange(n):
            s = raw_input()
            if s == 'stop':
                break
            result.append((s, len(s)))
        result = sorted(result, key=lambda x:x[1])
        for j, k in result:
            print j
except:
    pass

发表于 2016-12-28 18:12:32 回复(0)
//是基于第二位大神写的改了冒泡算法哪里
public class MaoPao {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			String str = scanner.nextLine();
			int strNum = Integer.valueOf(str);
			int count = 0;
			String[] strList = new String[strNum];
			for (int i = 0; i < strNum; i++) {
				strList[i] = scanner.nextLine();
				count++;
				if (strList[i].equals("stop")) {
					strList[i] = "";
					count--;
					break;
				}
			}
         //冒泡算法的另一种
                            //输入英文的个数,也是循环的个数
			for (int i = 1; i < strList.length; i++) {
                            //每次跟下一个比较,小的数提前,大的不变。
				for (int j = 0; j < strList.length - i; j++) {
					if (strList[j].length() > strList[j+1].length()) {
						String temp = strList[j];
						strList[j] = strList[j+1];
						strList[j+1] = temp;
					}
				}
			}
			for (int i = 0; i < count; i++) {
				System.out.println(strList[i]);
			}
		}
	}

}

编辑于 2016-09-26 15:52:33 回复(0)
#include<bits/stdc++.h>
int main(){
    int n,s;
    char b[100]={},a[100][100]={};
    while(scanf("%d",&n)!=EOF){//输入n后会有一个残留的换行符
        memset(b,0,sizeof(b));
        memset(a,0,sizeof(a));
        for(int i=0;i<=n;i++){//多循环一次以便吸收输入n后的换行符,也可用getchar
            gets(b);
            if(strcmp(b,"stop")==0)
                break;
            strcpy(a[strlen(b)],b);
        }
        for(int i=0;i<100;i++)
            if(a[i][0]!=0)
                puts(a[i]);
    }
}//还是Hash
编辑于 2019-03-07 11:32:08 回复(0)
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

bool cmp(string str1, string str2)
{
    return str1.length() < str2.length();
}

int main()
{
    string str;
    vector<string> v;
    int n;
    while(cin >> n)
    {
        getchar();      // 吸收 cin 之后的回车
        v.clear();
        while(n--)
        {
            getline(cin, str);
            // str == stop
            if(str == "stop")
            {
                break;
            }
            v.push_back(str);
        }
        sort(v.begin(), v.end(), cmp);
        for(int i = 0; i < v.size(); ++i)
        {
            cout << v[i] << endl;
        }
    }
    return 0;
}


发表于 2016-08-12 15:50:00 回复(3)
这道题最大的坑在于cin,getline(cin,str),cin.getline()对换行符使用的问题:
1.cin输入后是不去除后面的\n的
2.getline会将\n换成\0,并主动丢弃换行符
3.cin.getline()读取到\n会换成\0,但是会把换行符保留在输入队列中
代码实现方面只能说STL里的vector和sort真是太香了
#include<bits/stdc++.h>
using namespace std;
bool cmp(string s1,string s2){
    return s1.length()<s2.length();
}
int main(){
    int n;
    while(cin>>n){
        vector<string> vs;
        getchar();
        for(int i=0;i<n;i++){
            string str;
            getline(cin,str);
            if(str=="stop"){
                break;
            }
            vs.push_back(str);
        }
        sort(vs.begin(),vs.end(),cmp);
        for(vector<string>::iterator it=vs.begin();it!=vs.end();it++){
            cout<<*it<<endl;
        }
    }
    return 0;
}



发表于 2020-02-19 18:54:32 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(string str1, string str2){
    return str1.size() < str2.size();
}

int main() {
    int n;
    string str;
    vector<string> vec;

    while ((scanf("%d", &n)) != EOF) {

        getchar();  // 吸收回车
        vec.clear();    // 清空vector

        for(int i=0; i<n; ++i){

            getline(cin, str);  // 获取整行

            if(str == "stop")break;;
            vec.push_back(str);
        }

        sort(vec.begin(), vec.end(), cmp);

        for(auto &it:vec){
            cout << it << endl;
        }
    }
}
1.cin输入后是不去除后面的\n的
2.getline会将\n换成\0,并主动丢弃换行符
3.cin.getline()读取到\n会换成\0,但是会把换行符保留在输入队列中
摘自Finalize大佬

编辑于 2025-05-07 09:51:22 回复(0)
map
#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    int n;
    while(cin>>n){
        cin.ignore();
        map<int,vector<string>>mp;
        string str;
       for (int i = 0; i < n; ++i)
        {
            getline(cin, str);
            if (str == "stop")break;
            mp[str.size()].push_back(str);
         
    }
    for (const auto& pair :mp) {
        for (const string& s : pair.second) {
            cout << s << endl;
        }
    }
    }
}

发表于 2025-03-24 15:41:57 回复(0)
#include <bits/stdc++.h>
using namespace std;

bool comp(string a, string b) {
    return a.size() < b.size();
}

int main() {
    string s;
    int n;
    while (cin >> n) {
        cin.ignore();
        vector<string>vec;
        for (int i = 0; i < n; i++) {
            getline(cin, s);
            if (s == "stop")break;
            vec.push_back(s);
        }
        sort(vec.begin(), vec.end(), comp);
        for (auto it = vec.begin(); it != vec.end(); it++) {
            cout << *it << endl;
        }

    }
}
发表于 2025-03-19 20:52:30 回复(0)
读入字符串放入字符串数组,然后对字符串长度排序,输出即可。简单题。
需要注意cin>>int的时候,如果要再用getline获取缓冲区行作为字符串,需要使用cin.get()拿掉换行符。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(string str1,string str2){
	return str1.length()<str2.length();
}

int main(){
	int n;
	while(cin >> n){
		cin.get();//清除换行符
		string inputstr;//记录每行的输入
		vector<string> strVec;//字符串数组,保存所有输入
		for(int i=0;i<n;i++){
			getline(cin,inputstr);//每次获取一行
			if(inputstr=="stop"){
				break;
			}
			strVec.push_back(inputstr);//插入字符串数组
		}
		sort(strVec.begin(),strVec.end(),compare);
		for(int i=0;i<strVec.size();i++){
			cout << strVec[i] << endl;
		}
	}
	return 0;
}
发表于 2025-03-17 13:57:58 回复(0)
#include <iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

bool cmp(string a,string b){
    return a.size()<b.size();
}
int main() {
    int n,i;
    vector<string>ad;
    string str;
    while(cin>>n){
        cin.ignore();
        for(i=0;i<n;i++){
            getline(cin,str);
            if(str=="stop")
                break;
            ad.push_back(str);
        }
        sort(ad.begin(),ad.end(),cmp);
            for(int j=0;j<i;j++)
        		cout<<ad[j]<<endl;
        ad.clear();
    }
}

发表于 2025-02-18 21:18:15 回复(0)