Let's take a look at the definition of switch in C ++:
Values Based on Integer expressions can be selected from multiple parts of the Code.
switch ( expression ) case constant-expression : statement [default : statement]
Expression in SwitchIt must be an integer, character, or enumeration value.
That is to say, I cannot use it like this:
string s="123";switch(s){ case "1":{ break; } case "23":{ break; } 、、、}
This tangle (C #, JS can judge the string). In order to be able to use the switch statement, we can only match the string with the value one by one, but this is also very troublesome. For example:
int getIndex(std::string *s,std::string str){int index;for(int i=0;i<s->length();i++){if(s[i]==str){index=i;break;}}return index;}int main(){string str="12",ss;string s[10]={"123","12"};int i=getIndex(s,str);switch(i){case 1:{ss+="100";break;}default:{ss+="default";break;}}cout<<ss<<endl;}
This method is fine. You need to add a branch each time and add a string to the array, and then add a case for processing. Similar methods include:
int main(){string str="12",ss;int i;if(str=="12")i=1;if(str=="123")i=2;switch(i){case 1:{ss+="100";break;}default:{ss+="default";break;}}cout<<ss<<endl;}
This is the most direct method, but if there are many branches, there will be a lot of if statements. I personally prefer the first one. If you have a good method, please post it for discussion and study!
Author:Kunoy
Source:Http://blog.csdn.net/kunoy
Statement:The authors write blogs to sum up experience and exchange learning.
If you need to reprint the statement, please keep it as much as possible and provide the original article connection clearly on the article page. Thank you!