温馨提示×

如何用c++ string匹配实现字符串排序

c++
小樊
83
2024-09-25 08:59:14
栏目: 编程语言

你可以使用C++的<algorithm>库中的sort()函数对字符串进行排序。但是,如果你想使用字符串匹配来实现自定义的排序规则,你可以使用<regex>库和自定义比较函数。

下面是一个使用正则表达式和自定义比较函数对字符串进行排序的例子:

#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <algorithm>

// 自定义比较函数
bool compareStrings(const std::string& s1, const std::string& s2) {
    // 使用正则表达式提取数字
    std::regex num_regex(R"(\d+)");
    std::smatch match1, match2;

    // 查找第一个字符串中的所有数字
    if (std::regex_search(s1, match1, num_regex) && std::regex_search(s2, match2, num_regex)) {
        // 将找到的数字转换为整数并比较
        int num1 = std::stoi(match1.str());
        int num2 = std::stoi(match2.str());
        return num1 < num2;
    }

    // 如果一个字符串包含数字而另一个不包含,则认为包含数字的字符串较小
    return s1.find(num_regex) != std::string::npos;
}

int main() {
    // 要排序的字符串向量
    std::vector<std::string> strs = {"abc123", "def456", "ghi789", "jkl012", "mno345"};

    // 使用自定义比较函数对字符串进行排序
    std::sort(strs.begin(), strs.end(), compareStrings);

    // 输出排序后的字符串向量
    for (const auto& s : strs) {
        std::cout<< s << std::endl;

0