如何在c / c ++中将字符串中的字母排序为字母顺序? [英] How to sort the letters in a string into alphabetical order in c / c++?

查看:135
本文介绍了如何在c / c ++中将字符串中的字母排序为字母顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi all
在这段代码当我写AaBc它写'ABab'。
在这段代码中我应该改变什么,如果我想写它像'AaBb'???

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 '???

#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;
}


推荐答案

'A''a'不一样。 'A'== 65 'a'== 97

因此,比较时,您需要使用 tolower toupper 进行比较,以确保你的价值是对的。在进行比较之后,您需要然后也比较看它是上层还是小写(以确保上层,然后更低的排序)。

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

这篇关于如何在c / c ++中将字符串中的字母排序为字母顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆