Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Is there a way to switch on strings?
Is there a way to switch on strings?
✍: Guest
Not directly. Sometimes, it's appropriate to use a separate function to map strings to integer codes, and then switch on those:
#define CODE_APPLE 1
#define CODE_ORANGE 2
#define CODE_NONE 0
switch(classifyfunc(string)) {
case CODE_APPLE:
...
case CODE_ORANGE:
...
case CODE_NONE:
...
}
where classifyfunc looks something like
static struct lookuptab {
char *string;
int code;
} tab[] = {
{"apple", CODE_APPLE},
{"orange", CODE_ORANGE},
};
classifyfunc(char *string)
{
int i;
for(i = 0; i < sizeof(tab) / sizeof(tab[0]); i++)
if(strcmp(tab[i].string, string) == 0)
return tab[i].code;
return CODE_NONE;
}
Otherwise, of course, you can fall back on a conventional if/else chain:
if(strcmp(string, "apple") == 0) {
...
} else if(strcmp(string, "orange") == 0) {
...
}
2015-02-04, 1206👍, 0💬
Popular Posts:
How To Control Horizontal Alignment? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells By...
What is Windows DNA architecture? Note :- If you have worked with classic ASP this question can come...
What are the two kinds of comments in JSP and what's the difference between them? <%-- JSP Co...
How To Truncate an Array? - PHP Script Tips - PHP Built-in Functions for Arrays If you want to remov...
Which bit wise operator is suitable for turning off a particular bit in a number? The bitwise AND op...