gpt4 book ai didi

c++ - 如何不区分大小写地排序字符串(不是字典顺序)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:47:24 25 4
gpt4 key购买 nike

我正在尝试按字母顺序(而不是字典顺序)对文件中的列表输入进行排序。所以,如果列表是:

CdA

我需要它变成:AbC

不是字典顺序:ACb

我正在使用字符串变量来保存输入,所以我正在寻找一些方法来修改我正在比较的字符串是否全部大写或小写,或者如果有一些更简单的方法来强制进行字母比较,请传授那智慧。谢谢!

我还应该提到,我们仅限于以下库来完成此作业:iostream、iomanip、fstream、string,以及 C 库,如 cstring、cctype 等。

最佳答案

It looks like I'm just going to have to defeat this problem via some very tedious method of character extraction and toppering for each string.

将单个字符串转换为大写并比较它们并不会因为使用算法、迭代器等受到限制而变得特别糟糕。比较逻辑大约有四行代码。尽管不必写那四行代码会很好,但不得不编写排序算法要困难得多,也更乏味。 (好吧,假设通常的 C 版本的 toupper 首先是可以接受的。)

下面我展示了一个简单的 strcasecmp() 实现,然后将其用于一个使用受限库的完整程序。 strcasecmp() 的实现本身不使用受限库。

#include <string>
#include <cctype>
#include <iostream>

void toupper(std::string &s) {
for (char &c : s)
c = std::toupper(c);
}

bool strcasecmp(std::string lhs, std::string rhs) {
toupper(lhs); toupper(rhs);
return lhs < rhs;
}

// restricted libraries used below

#include <algorithm>
#include <iterator>
#include <vector>

// Example usage:
// > ./a.out <<< "C d A b"
// A b C d
int main() {
std::vector<std::string> input;
std::string word;
while(std::cin >> word) {
input.push_back(word);
}

std::sort(std::begin(input), std::end(input), strcasecmp);
std::copy(std::begin(input), std::end(input),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << '\n';
}

关于c++ - 如何不区分大小写地排序字符串(不是字典顺序)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com