【问题标题】:Program To Identify Lower Case Strings识别小写字符串的程序
【发布时间】:2016-03-10 20:51:14
【问题描述】:

这里是 C++ 初学者,第一次上编程课。我正在尝试编写一个程序来识别字符串是否全部小写。我得到了下面的代码。但是,我需要考虑空格“”。如果用户输入的字符串中有空格,则程序假定返回它不是全部小写。示例:

输入:abc def return:字符串不是小写的。

你们中的任何人是否会这么好心地建议在下面的代码中解决这个问题的最佳方法是什么?

注意:我知道我已经“包含”了一些额外的头文件,但那是因为这将成为另一个程序的一部分,这只是让事情运行的摘录。

非常感谢大家!!

 #include <fstream>
 #include <iostream>
 #include <string>
 #include <cstdlib>
 #include <algorithm>
 #include <cctype>
 #include <iomanip>

 using namespace std;

 bool die(const string & msg);


 bool allLower(const string & l);

 int main() {

     string l;

    cout << "\nEnter a string (all lower case?): ";
     cin >> l;

     if (allLower(l) == true)
     {
         cout << "The string is lower case." << endl;
     }
     else
     {
         cout << "The string is not lower case." << endl;
     }



 }



 bool allLower(const string & l) {

     struct IsUpper {
         bool operator()(int value) {
             return ::isupper((unsigned char)value);
         }
     };

     return std::find_if(l.begin(), l.end(), IsUpper()) == l.end();

 }

 bool die(const string & msg){
     cout << "Fatal error: " << msg << endl;
     exit(EXIT_FAILURE);
 }

【问题讨论】:

  • 就像::isupper 有类似::isspace 的函数来检查空格

标签: c++ string boolean uppercase lowercase


【解决方案1】:

你可以使用老式的 for 循环。

bool allLower(const std::string & l)
{
    for(unsigned int i = 0; i < l.size(); i++)
    {
        if(l[i] == ' ')
        {
            return false;
        }
        else if(isalpha(l[i]))
        {
            if(isupper(l[i]))
                return false;
        }
    }
    return true;
}

请注意,如果您输入“2”之类的内容,它将返回 true。如果你愿意,你可以添加一个返回 false 的最终 else 语句。

【讨论】:

    【解决方案2】:

    在使用 std::isupper() 或 std::islower() 检查字符串中的所有字母是否都是大写/小写之前,您可以使用函数 std::isalpha() 检查字符是否为字母等

    【讨论】:

      【解决方案3】:

      基于范围的 for 循环比索引 IMO 更清晰

      bool allLower(const std::string &l)
      {
          for (auto c : l)
          {
              if ((c == ' ') ||
                  (std::isalpha(c) && std::isupper(c)))
              {
                  return false;
              }
          }
          return true;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多