是否有办法将 char 测试为 class 的用户定义字符?
If there a way to test a char to a class of user define character?
有什么方法可以定义类型并执行以下操作吗?
char c = 'a';
if (c == BRASSECHARTYPE)
{
// do something if c is one of the following char [{()}]
}
您可以使用 std::string::find
来检查字符是否等于 [{()}]
:
#include <string>
#include <iostream>
int main(){
char needle = 'c';
std::string haystack = "[](){}";
if (haystack.find(needle) != std::string::npos) {
std::cout << needle << " was found in " << haystack << "\n";
}
}
有很多方法可以做到:
简单函数:
bool isOneOfChars(char ch, std::initializer_list<char> chars)
{
return std::find(std::begin(chars), std::end(chars), ch) != std::end(chars);
}
bool isBrace(char ch)
{
return isOneOfChars(ch, {'[', '{', '(', ')', '}'});
}
带有折叠表达式的精美模板:
template<char...Chars>
constexpr bool isOneOfChars(char ch)
{
return ((Chars == ch) || ...);
}
constexpr bool isBrace(char ch)
{
return isOneOfChars<'[', '{', '(', ')', '}'>(ch);
}
或使用指定的初始化查找 table(clangs 支持它):
constexpr bool isBrace(char ch)
{
constexpr bool braceTable[256] {
['['] = true,
['{'] = true,
['('] = true,
[')'] = true,
['}'] = true,
};
return braceTable[static_cast<unsigned char>(ch)];
}
或任何其他解决方案。
有什么方法可以定义类型并执行以下操作吗?
char c = 'a';
if (c == BRASSECHARTYPE)
{
// do something if c is one of the following char [{()}]
}
您可以使用 std::string::find
来检查字符是否等于 [{()}]
:
#include <string>
#include <iostream>
int main(){
char needle = 'c';
std::string haystack = "[](){}";
if (haystack.find(needle) != std::string::npos) {
std::cout << needle << " was found in " << haystack << "\n";
}
}
有很多方法可以做到:
简单函数:
bool isOneOfChars(char ch, std::initializer_list<char> chars)
{
return std::find(std::begin(chars), std::end(chars), ch) != std::end(chars);
}
bool isBrace(char ch)
{
return isOneOfChars(ch, {'[', '{', '(', ')', '}'});
}
带有折叠表达式的精美模板:
template<char...Chars>
constexpr bool isOneOfChars(char ch)
{
return ((Chars == ch) || ...);
}
constexpr bool isBrace(char ch)
{
return isOneOfChars<'[', '{', '(', ')', '}'>(ch);
}
或使用指定的初始化查找 table(clangs 支持它):
constexpr bool isBrace(char ch)
{
constexpr bool braceTable[256] {
['['] = true,
['{'] = true,
['('] = true,
[')'] = true,
['}'] = true,
};
return braceTable[static_cast<unsigned char>(ch)];
}
或任何其他解决方案。