我正在尝试使用 compare 方法按字母顺序排序一些字符串 . 问题是,例如,如果我想通过使用 b.compare(a) 将单词 string a = "Midnight" (大写m)与单词 string b = "apple" 进行比较,则返回 1 ,但我想将返回值设为 -1 ,这个问题有什么解决办法吗?
compare
b.compare(a)
string a = "Midnight"
string b = "apple"
1
-1
解决这个问题的一种方法是将两个字符串更改为大写,这样可以保证所需的比较输出 .
为你的例子:
string a = "Midnight"; string b = "apple"; for (auto &c: a) c = toupper(c); for (auto &c: b) c = toupper(c); b.compare(a) // returns -ve value;
您可以从此链接了解更多toupper()的工作原理 .
1 回答
解决这个问题的一种方法是将两个字符串更改为大写,这样可以保证所需的比较输出 .
为你的例子:
您可以从此链接了解更多toupper()的工作原理 .