首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何按字母顺序排列字符串?

如何按字母顺序排列字符串?
EN

Stack Overflow用户
提问于 2013-08-31 21:44:09
回答 6查看 120.2K关注 0票数 0

我一直试图使用这个c++程序按字母顺序对5个名称进行排序:

代码语言:javascript
复制
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;

int main()
{
char names[5][100];
int x,y,z;

char exchange[100];

cout << "Enter five names...\n";

for(x=1;x<=5;x++)
{
    cout << x << ". ";
    cin >> names[x-1];
}
getch();

for(x=0;x<=5-2;x++)
{
    for(y=0;y<=5-2;y++)
    {
        for(z=0;z<=99;z++)
        {
            if(int(names[y][z])>int(names[y+1][z]))
            {   
                strcpy(exchange,names[y]);
                strcpy(names[y],names[y+1]);
                strcpy(names[y+1],exchange);
                break;
            }
        }   
    }
}   

for(x=0;x<=5-1;x++)
    cout << names[x];

return 0;
}

如果我分别进入厄尔、唐、克里斯、比尔和安迪,我就明白了:

代码语言:javascript
复制
AndyEarlDonChrisBill

有人能告诉我我的节目有什么问题吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-09-03 01:46:14

您可以使用std::set或std::multiset (如果允许重复项的话),它将保持项目自动排序(如果您愿意,甚至可以更改排序条件)。

代码语言:javascript
复制
#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

int main()
{
    std::set<std::string> sortedItems;

    for(int i = 1; i <= 5; ++i)
    {
        std::string name;
        std::cout << i << ". ";
        std::cin >> name;

        sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
    return 0;
}

投入:

  1. 杰拉多
  2. 卡洛斯
  3. 卡米洛
  4. 天使
  5. 博斯科

产出:

代码语言:javascript
复制
Angel
Bosco
Carlos
Gerardo
Kamilo
票数 10
EN

Stack Overflow用户

发布于 2017-05-05 10:49:53

您可以使用排序函数:

代码语言:javascript
复制
#include <algorithm>
#include <vector>
using namespace std;

...

vector<string> s;
sort(s.begin(),s.end());
票数 8
EN

Stack Overflow用户

发布于 2016-11-15 20:31:39

你使用了太多不必要的循环。试试这个简单有效的。当字符串按字母顺序比其他字符串慢时,您只需要交换。

代码语言:javascript
复制
Input
5
Ashadullah
Shawon
Shakib
Aaaakash
Ideone

Output
Aaaakash
Ashadullah
Ideone
Shakib
Shawon


#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s[200],x[200],ct,dt;
    int i,j,n;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>s[i];
    }

    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {

            if(s[i]>s[j])
            {

                ct=s[i];
                s[i]=s[j];
                s[j]=ct;

            }

        }

    }
    cout<<"Sorted Name in Dictionary Order"<<endl;
    for(i=0;i<n;i++)
    {
        cout<<s[i]<<endl;
    }
    return 0;


}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18553097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档