将字符与C中的多个字符进行比较 [英] Compare character with multiple characters in C
问题描述
我如何比较C中的角色与其他角色,而不使用'if'
和吨'||'?
例如,假设我有一个名为'i'的字符,我希望与其他8个字符进行比较,这些字符之间没有任何关联,如果'i'等于这8个字符中的至少一个,那么表达式是真的。
这样的事情:
How can i compare a character in C with other characters without using an 'if' with tons of '||'? For example let's say I have a character named 'i' that I want to compare with 8 other characters that have no connection between them whatsoever, and if 'i' equals to at least one of those 8 characters then the expression is true. Something like this:
if(i == c1 || i == c2 || i == c2 ........){ /* do stuff */}
但是很大应用程序这些比较很多,而不仅仅是3或8.
有没有一种智能而快速的方法来实现这样的东西而不是最终看起来丑陋的代码?提前谢谢你。
But on a big application these comparisons are a lot, not just 3 or 8. Is there a smart and fast way to achieve something like this and not end up with ugly looking code? Thank you in advance.
推荐答案
假设你的'c1'
,. ..只是一个 char
常量,你可以使用:
Assuming your 'c1'
, ... are just a single char
constants, you can use:
if ( strchr("12345", ch) != NULL )
...
(12345是 c1
, c2
,...)
("12345" are c1
, c2
, ...)
strchr()
也会匹配implcit尾随NUL终结符('\ 0'
)。如果这是一个问题,您可以显式比较此值。从开始搜索输入字符串时,您可能希望在开头有更多可支持的值。
strchr()
will, however, also match the implcit trailing NUL terminator ('\0'
). If that is a problem, you can compare this value explicitly. As the input string is searched from start, you might want to have the more propable values at the beginning.
请注意 strchr
确实返回指向匹配char的指针;只要你需要它。
Note that strchr
does return a pointer to the matching char; just if you need that.
如果你可以对这些值进行分组,例如字母,数字等等,请查看 ctype.h 。
If you can group the values, e.g. "letters", "digits", etc., have a look at ctype.h.
如果值是变量,您可以在比较之前将它们复制到 char
的数组中(不要忘记trminator!)或者将它们保存在数组中: array [0]
是 c1
,...。
If the values are variables, you can either copy them into an array of char
before the compare (do not forget about the trminator!) or hold them in the array anyway: array[0]
is c1
, ... .
如果无法做到这一切,你很可能会遇到 strcpy
。你可以使用这个:
If all this is not possible, you are likely busted with strcpy
. You could use this:
// assuming there are always the same variables used.
static const char * const ca[] = { &c1, &c2, ... };
char val;
for ( size_t i = 0 ; i < sizeof(ca) / sizeof(ca[0]) ; i++ ) {
if ( *ca[i] == val ) {
// match!
}
}
您可以将其打包到一个带有一些装饰的功能中那里。
You could pack that into a function with some decoration here and there.
这篇关于将字符与C中的多个字符进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!