我正在开发一个代码,将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
}

最佳答案

关于什么:

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

这是一个online demo

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

08-16 02:14