【问题标题】:How do I sort capital letters as well in C++ [closed]如何在 C++ 中也对大写字母进行排序 [关闭]
【发布时间】:2020-06-26 22:04:26
【问题描述】:

我已经编写了一个程序,它打算接受一个输入并按字符的升序返回输出。

例子:

场景 1:给定输入“Hello Rohit”,该方法应返回“ehHillooRt”

场景 2:给定输入“Hello Rohit!”,该方法应返回错误消息(“Invalid character ! at position 12”),指定第一次出现和无效字符的位置。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    int i, count, n;
    cout << "Enter a sentence : ";
    getline(cin, str);
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] == ' ')
            count++;
    }
    string strWords[count + 1];
    short counter = 0;
    for (short i = 0; i < str.length(); i++) {
        if (str[i] == ' ') {
            counter++;
            i++;
        }
        strWords[counter] += str[i];
    }
    for (i = 0; i < strWords[i].length(); i++) {
        string temp = strWords[i];
        sort(temp.begin(), temp.end());
        cout << temp << " ";
    }
    return 0;
}

【问题讨论】:

  • 请修正你的缩进(做缩进)和垂直间距(你不需要所有的垂直空间)。这将使代码更易于阅读。
  • 与您的问题无关,但请花点时间阅读Why should I not #include <bits/stdc++.h>?
  • 还要注意 C++ 没有variable-length arrays。使用例如std::vector 代替。
  • 问题陈述不要求将输入拆分为单词。 "Hello Rohit" -&gt; "ehHillooRt" 的示例显然忽略了单词边界(注意两个 os 如何在输出中一起出现)。大约五分之四的代码专门用于拆分成单词。
  • 请花点时间刷新How to Ask,以及this question checklist。您显示的代码有什么问题?对于您作为示例提供的输入,actual 输出是什么?当你构建或运行你的程序时会发生什么?您是否尝试过在调试器中逐句逐句执行代码?

标签: c++ string sorting c++11


【解决方案1】:

您可以使用std::sort 和lambda,其中字符使用小写 (std::tolower) 进行比较

#include <algorithm>
#include <iostream>

int main()
{
  std::string str;
  std::cout << "Enter a sentence : ";
  getline(std::cin, str);

  std::sort(str.begin(), str.end(), [](const char& a, const char& b) {
    if (std::tolower(a) == std::tolower(b))
      return a > b;
    else
      return std::tolower(a) < std::tolower(b);
  });
  std::cout << str << std::endl;

  return 0;
}

这会显示

Enter a sentence : Hello Rohit
 ehHillooRt

在终端中。请注意,空格排序在所有字母的前面。如果要删除空格,可以使用以下代码行:

str.erase(std::remove_if(str.begin(), str.end(), [](unsigned char x) { return std::isspace(x); }), str.end());

如果您还想检查不需要的元素,可以使用:

std::vector<std::string> unwanted_elements{ "!" }; // Coma separed list of strings that you don't want in the input. Note that this are full strings so you could also reject "Hello" for instance.

for (size_t i = 0; i < unwanted_elements.size(); ++i)
{
  size_t idx = str.find(unwanted_elements[i]);
  if (idx != std::string::npos)
  {
    std::cout << "Unwnated element " << unwanted_elements[i] << " at position " << idx << std::endl;
  }
} 

那么整个程序就是:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::string str;
  std::cout << "Enter a sentence : ";
  getline(std::cin, str);

  std::vector<std::string> unwanted_elements{ "!" }; // Coma separed list of strings that you don't want in the input. Note that this are full strings so you could also reject "Hello" for instance.

  for (size_t i = 0; i < unwanted_elements.size(); ++i)
  {
    size_t idx = str.find(unwanted_elements[i]);
    if (idx != std::string::npos)
    {
      std::cout << "Unwnated element " << unwanted_elements[i] << " at position " << idx << std::endl;
      return -1;
    }
  }

  str.erase(std::remove_if(str.begin(), str.end(), [](unsigned char x) { return std::isspace(x); }), str.end());

  std::sort(str.begin(), str.end(), [](const char& a, const char& b) {
    if (std::tolower(a) == std::tolower(b))
      return a > b;
    else
      return std::tolower(a) < std::tolower(b);
  });
  std::cout << str << std::endl;

  return 0;
}

此解决方案仅适用于纯 ascii 字符。

【讨论】:

  • lambda 可以很容易地写成:return std::tolower(a) &lt; std::tolower(b);
  • 不,那么大写就不会出现在小写之后(在他的例子中:Hello Rohit -> ehHillooRt)
  • 确实如此,但请注意,您假设在字符集的整理顺序中小写字符跟随大写,如果使用另一个字符集,情况并非总是如此。您应该在答案中指出这一点。
  • 我没有关注你。您是指用户输入的字符序列(即std::string str 中的字符)还是代表它的数值?我一直假设 C++ 中的字符比较是使用字符 ascii 值完成的。在这种情况下,大写字母将始终“小于”小写字母。
  • 您的解决方案是可移植的,只要您使用std:: 函数进行字符确定。一旦你通过严格比较假设字符 a 大于字符 b,即a &gt; b,你就使解决方案不可移植。不要误会,您的解决方案适用于 ASCII,但可能不适用于其他字符集(例如 EBCDIC)
猜你喜欢
  • 2018-06-14
  • 2017-11-21
  • 2016-12-21
  • 1970-01-01
  • 2013-02-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多