我正在开发一个代码来将 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()
) .如果它是有效的,因为你不区分小写和大写,我们将转换字符 toupper()
.由于您的返回值是按字母顺序排列的,因此我们只需要减去第一个字母即可。
关于c++ - 减少 if-elseif 语句的聪明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272324/