巧妙地减少if-elseif语句的方法

Cro*_*oCo 3 c++ string if-statement control-flow

我正在开发一个代码来将SpinBox限制为字母而不是整数.一切都运行正常,但如果有任何聪明的方法,我想减少if-elseif语句.这是代码

std::string AlphaSpinBox::textFromValue(int value) 
{
    // I feel the code is Ok but willing to change it if there is a better way.
    // value is restricted [0-25] inclusive. 
    std::string str("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    return std::string(str[value]);
}

int AlphaSpinBox::valueFromText(std::string &text) 
{
    // can I shorten the following?!
    // text is solely one letter (i.e. either upper or lower)
    if(text == 'A' || text == 'a')
        return 0;
    else if(text == 'B' || text == 'b' )
        return 1;
    else if(text == 'C' || text == 'c')
        return 2;
    else if(text == 'D' || text == 'd')
        return 3;
    ... to z letter
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*phe 7

关于什么:

 if (text.size()>0 && std::isalpha(text[0]))
     return std::toupper(text[0])-'A'; 
 else return -1;    // or throw an exception 
Run Code Online (Sandbox Code Playgroud)

这是一个在线演示.

工作原理:首先检查字符串是否为空,第一个字符是否为字母(带isalpha()).如果它是有效的,因为你在小写和大写之间没有区别,我们转换char toupper().由于您的返回值按字母顺序排列,我们只需要减去第一个字母.