c++ - 如何在c / c ++中将字符串中的字母按字母顺序排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6083432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:27:22  来源:igfitidea点击:

How to sort the letters in a string into alphabetical order in c / c++?

c++csorting

提问by KoolKabin

hi all in this code when i write AaBc it writes ' ABab' . what should i change in this code ,if i want it writes like ' AaBb '???

大家好,当我写 AaBc 时,这段代码写的是 'ABab' 。如果我希望它写成“AaBb”,我应该在此代码中更改什么???

#include <stdlib.h>
#include<iostream.h>
#include<string.h>
int main (void)
{
    char string[128], temp;
    int n, i, j;

    printf("\nEnter string: ");
    gets(string);

    n = strlen(string);

    for (i=0; i<n-1; i++)
    {
        for (j=i+1; j<n; j++)
        {
            if (string[i] > string[j])
            {
                temp = string[i];
                string[i] = string[j];
                string[j] = temp;
            }
        }
    }
    printf("\n%s", string);
    printf("\n");
    return 0;
}

回答by pickypg

The ASCII value of 'A'and 'a'are not the same. 'A' == 65and 'a' == 97.

的ASCII值'A''a'是不一样的。'A' == 65'a' == 97

So, when you compare, you need to compare using either toloweror toupperto make sure that your value is right. After you make that comparison, you need to thenalso compare to see if it's upper versus lowercase (to ensure upper, then lower ordering).

因此,当您进行比较时,您需要使用其中之一进行比较,tolower或者toupper确保您的值是正确的。你作出这样的对比之后,你需要还比较一下,看它是否上与小写(保证上,然后下订单)。

回答by Gilbert

You first need to do a case insensitive comparison and, if the letters are the same, a case sensitive comparison.

您首先需要进行不区分大小写的比较,如果字母相同,则进行区分大小写的比较。

#include <stdlib.h>
#include<iostream.h>
#include<string.h>
int main (void)
{
    char string[128], temp;
    int n, i, j;

    printf("\nEnter string: ");
    gets(string);
    n = strlen(string);

    for (i=0; i<n-1; i++)
    {
        for (j=i+1; j<n; j++)
        {
            int  s = tolower(string[i]) - tolower(string[j]);
            if ( s == 0 )
            {   // letters are the same... now watch out for case
                s = string[i] - string[j];
            }

            if (s > 0)
            {
                temp = string[i];
                string[i] = string[j];
                string[j] = temp;
            }
        }
    }
    printf("\n%s", string);
    printf("\n");
    return 0;
}

回答by deong

You need a customer comparison function to pass to sort (or qsort).

您需要一个客户比较函数来传递给排序(或 qsort)。

bool comp(char c1, char c2)
{
    return tolower(c1) < tolower(c2);
}

int main()
{
    std::string str = "ABab";
    std::sort(str.begin(), str.end(), comp);
    cout << str << endl;
    return 0;
}