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

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

问题描述

大家好
在这code当我写AABC其写入ABAB。
我应该在这个code改变,如果我想它写得像AABB???

 的#include<&stdlib.h中GT;
#包括LT&;&iostream.h时GT;
#包括LT&;&string.h中GT;
INT主要(无效)
{
    字符字符串[128],温度;
    INT N,I,J;    的printf(\\ n输入字符串:);
    得到(字符串);    N = strlen的(字符串);    对于(i = 0; I< N-1;我++)
    {
        为(J = I + 1; J< N; J ++)
        {
            在(string [I]>字符串[J]。)
            {
                TEMP =字符串[我]
                字符串[我] =字符串[J]。
                字符串[J] =温度;
            }
        }
    }
    的printf(\\ N%的字符串);
    的printf(\\ n);
    返回0;
}


解决方案

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

所以,当你比较,你需要使用用来比较 tolower的 TOUPPER ,以确保你的价值是对的。您作出这样的对比之后,你需要的然后的还比较一下,看它是否与上小写(保证上,然后放下排序)。

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

解决方案

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

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天全站免登陆