你可以使用C++的<algorithm>
庫中的sort()
函數(shù)對字符串進行排序。但是,如果你想使用字符串匹配來實現(xiàn)自定義的排序規(guī)則,你可以使用<regex>
庫和自定義比較函數(shù)。
下面是一個使用正則表達式和自定義比較函數(shù)對字符串進行排序的例子:
#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <algorithm>
// 自定義比較函數(shù)
bool compareStrings(const std::string& s1, const std::string& s2) {
// 使用正則表達式提取數(shù)字
std::regex num_regex(R"(\d+)");
std::smatch match1, match2;
// 查找第一個字符串中的所有數(shù)字
if (std::regex_search(s1, match1, num_regex) && std::regex_search(s2, match2, num_regex)) {
// 將找到的數(shù)字轉(zhuǎn)換為整數(shù)并比較
int num1 = std::stoi(match1.str());
int num2 = std::stoi(match2.str());
return num1 < num2;
}
// 如果一個字符串包含數(shù)字而另一個不包含,則認(rèn)為包含數(shù)字的字符串較小
return s1.find(num_regex) != std::string::npos;
}
int main() {
// 要排序的字符串向量
std::vector<std::string> strs = {"abc123", "def456", "ghi789", "jkl012", "mno345"};
// 使用自定義比較函數(shù)對字符串進行排序
std::sort(strs.begin(), strs.end(), compareStrings);
// 輸出排序后的字符串向量
for (const auto& s : strs) {
std::cout<< s << std::endl;