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, 1517👍, 0💬
Popular Posts:
Write an equivalent expression for x%8? x&7
How To Blend a Color Layer to a Image? - PSP Tutorials - Fading Images to Background Colors with PSP...
What is AL.EXE and RESGEN.EXE? In the previous question you have seen how we can use resource files ...
Can you explain duplex contracts in WCF? In duplex contracts when client initiates an operation the ...
Where are all .NET Collection classes located ? System.Collection namespace has all the collection c...