c++ - 用数字对 std::strings 进行排序?

标签 c++ string sorting

我目前正在按 std::string < 运算符排序。它的问题在于:

30 < 9。30 出现在 9 之前,因为 3 < 9,Windows 9x 有这个问题。我怎样才能对它们进行数字排序,以便“30 只狐狸”出现在“9 只狗”之后。我还应该补充一点,我使用的是 utf 8 编码。

谢谢

最佳答案

您可以创建自定义比较函数以与 std::sort 一起使用。此函数必须检查字符串是否以数字值开头。如果是,则使用某种机制(如字符串流)将每个字符串的数字部分转换为 int。然后比较两个整数值。如果值相等,则按字典顺序比较字符串的非数字部分。否则,如果字符串不包含数字部分,只需照常按字典顺序比较两个字符串。

基本上,类似于以下(未经测试的)比较函数:

bool is_not_digit(char c)
{
    return !std::isdigit(c);
}

bool numeric_string_compare(const std::string& s1, const std::string& s2)
{
    // handle empty strings...

    std::string::const_iterator it1 = s1.begin(), it2 = s2.begin();

    if (std::isdigit(s1[0]) && std::isdigit(s2[0])) {
        int n1, n2;
        std::stringstream ss(s1);
        ss >> n1;
        ss.clear();
        ss.str(s2);
        ss >> n2;

        if (n1 != n2) return n1 < n2;

        it1 = std::find_if(s1.begin(), s1.end(), is_not_digit);
        it2 = std::find_if(s2.begin(), s2.end(), is_not_digit);
    }

    return std::lexicographical_compare(it1, s1.end(), it2, s2.end());
}

然后……

std::sort(string_array.begin(), string_array.end(), numeric_string_compare);

编辑:当然,只有当您对数字部分出现在字符串开头的字符串进行排序时,此算法才有用。如果您要处理数字部分可以出现在字符串中任何地方 的字符串,那么您需要更复杂的算法。参见 http://www.davekoelle.com/alphanum.html获取更多信息。

关于c++ - 用数字对 std::strings 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4622516/

相关文章:

php - 如何从文本文件中读取直到找到字符串并删除文本直到找到下一个特定字符串?

sorting - 数据表 - 将其中一列格式化为货币

java - 按从最高-> 最低的每个字符串解析的整数对 ArrayList<String> 进行排序?

python - numpy从上到下排序

c++ - 当文件为 Windows (\r\n) 格式化时,为什么 fstream::tellg() 返回值被输入文本文件中的换行符数放大?

c++ - 我的代码会安全地检查下溢吗?

c# - 在互操作(C++ 管理)项目中使用 C# dll(使用 Microsoft.bcl 构建)

javascript - 将字符串拆分为每个索引 n 个单词的数组

c - 程序运行时出现段错误

c++ - 定义一个类的不确定数量的实例