【问题标题】:Checks if an input , a string, has Roman numerals检查输入,一个字符串,是否有罗马数字
【发布时间】:2019-04-09 10:13:11
【问题描述】:

一个函数,它接受一个字符串作为输入,如果该字符串只包含 罗马数字,否则为假。回想一下,罗马数字是 M、D、C、L、 X、V 和 I。

这就是我目前所拥有的

bool isRoman(string str, char key)
 {

 assert(str.length() > 0)

 if(length[i] == key)
  {

  return i;
  } 
 }

【问题讨论】:

  • 什么是ikey 是什么?
  • 至少你已经开始了。这里看起来有一些错误,即使用了未定义的变量i,而不是函数的所有控制路径都返回值。你有问题吗?
  • 您的标题显示“对字符串进行排序”。但是你的描述没有提到排序。
  • assert() 只会在调试模式下被捕获...发布不会命中那个。我建议做类似 if(str.empty()) { return false; } 然后继续...
  • @JE3 如果该字符串仅包含罗马数字则为真 -- 您确定您阅读的描述正确吗?这是一个字符串——“LLLLLL”——是罗马数字吗?或者这里是另一个字符串——“XX II”——包含罗马数字,其中两个。因此,您需要进一步澄清一下这个作业应该做什么。

标签: c++ arrays boolean


【解决方案1】:

如果您只想知道std::string 是否仅包含来自特定有效字符集的值,您可以使用std::string::find_first_not_of。这使您的功能成为单行:

bool isRoman(const std::string &str)
{
    return !str.empty() && str.find_first_not_of("MDCLXVI") == std::string::npos;
}

【讨论】:

    【解决方案2】:
    #include <cctype>
    #include <string>
    #include <string_view>
    
    using namespace std::string_literals;
    
    bool is_roman(std::string_view sv)
    {                             // if the character is not found in the string
        for(auto const &ch : sv) //  containing roman numeric symbols, return false.
            if ("MDCLXVI"s.find(std::toupper(static_cast<unsigned>(ch))) == std::string::npos)
                return false;
        return true;
    }
    

    【讨论】:

    • 我会调用 strupr(number),而不是 std::toupper() 每个函数调用每个字符。
    • 您可以先使用std::transformstd::toupper 来转换字符串。
    • 我也不喜欢这个功能。它不能正常工作。如果 number 为 null 并且它将跳过 while(*number) 并返回 true.... 函数应该是 isRoman() 没有人会在它们之间创建带有 _ 的函数(这更像是一个变量名)跨度>
    • @OmidCompSCI strupr() 不是标准的。
    • @OmidCompSCI 没有人会在函数名称中使用“_”吗?你看过 C++ 标准库吗?
    【解决方案3】:

    一个不使用额外标准库的演示。

    #include <stdexcept>
    #include <cctype>
    #include <string>
    using namespace std;
    
    bool isRoman(string s){
        if(s.empty()){
            throw std::runtime_error("Got empty string");
        }
        bool isAllRoman = true;
        for(const auto& c: s){
            if(isspace(c)) //if you need to skip whitspace 
                continue;  
            if(!(c == 'M' || c == 'D' || c == 'C' || 
            c == 'L' || c == 'X' || c == 'V' || c == 'I')){
                isAllRoman = false;
                break;
            }
        }
        return isAllRoman;
    }
    

    有什么不明白的可以留言。

    【讨论】:

    • 您可以返回 false 而不是 isAllRoman = false。不需要boolean。
    • 每个函数最好有一个返回路径....我喜欢它的方式。
    • @OmidCompSCI 在您看来,也许。这是一个备受争议的话题。
    • @Rick 不要将潜在的负值传递给来自&lt;cctype&gt; 的函数。
    • @OmidCompSCI 如果函数在抛出之前返回,它不会抛出。抱歉,你说的是废话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多