简体   繁体   English

如何使用switch语句?

[英]How do I use the switch statement?

I am trying to understand the switch statement better. 我试图更好地理解switch语句。 I don't need the code but kinda a walkthrough on how it would be done. 我不需要代码,但是有点像如何实现的演练。

If someone enters a 7 digit phone number EG. 如果有人输入7位数的电话号码EG。 555-3333 but enters it as "jkl-deff" as it would correspodnd to the letters on the dial pad, how would I change the output back to numbers? 555-3333,但将其输入为“ jkl-deff”,因为它对应于拨号盘上的字母,我如何将输出更改回数字?

Would this work: 这项工作会:

switch (Digit[num1])
  case 'j,k,l':
              num1 = 5;
              break;
  case 'd,e,f':
              num1 = 3;
              break;

To do that with a switch statement, you'd have to walk through the char array, switching on each character. 要使用switch语句执行此操作,您必须遍历char数组,打开每个字符。 Group all the chars that have the same number together. 将具有相同编号的所有字符分组在一起。

Something like 就像是

switch (phoneChar[i])
case 'a':
case 'b':
case 'c':
   newChar[i] = '2';
   break;

That said, I'm not sure that switch case is the best way to do that. 就是说,我不确定切换盒是执行此操作的最佳方法。 I don't know what would be the best off the top of my head, but something feels wrong about this :) 我不知道什么是最好的选择,但是这有点不对劲:)

Edit The i would be the index of the current character under consideration. 编辑 i是正在考虑的当前字符的索引。 You'll have a 7 (or 8 or 10 or 12 character string depending on formatting) for a phone number. 您将使用7(或8、10或12个字符串,具体取决于格式)的电话号码。 You'd have to take each character at a time.. so phone[0] = 'j' in the above example. 您必须一次获取每个字符。.因此,在上面的示例中,phone [0] ='j'。

I would not use a switch! 我不会使用开关!

// A,B,C => 2;  D,E,F => 3 etc.
static int  convert[] = {2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};


for(int loop =0 ;loop < Digit.size(); ++loop)
{
    num = convert[Digit[loop] - 'a'];
                  // Thus the character 'a' gets mapped to position 0
                  //      the character 'b' gets mapped to position 1 etc.
    // num is then the character mapped into the covert[] array above.  
}

You could probably do it like this: 您可能会这样做:

if (islower(c)) { num=(c-'a')/3; num = 2 + (num==8) ? 7 : num; }

to convert a character to a phone pad digit. 将字符转换为电话键盘数字。 The num==8 part at the end handles the exra digit on the 9 key. 末尾的num == 8部分处理9键上的多余数字。

Altogether it would look like this: 总共看起来像这样:

char c = getNextCharacterSomehow();
int num = -1;

if (isdigit(c)) num = c-'0';
else if (islower(c)) { num=(c-'a')/3; num = 2 + (num==8) ? 7 : num; }
else if (isupper(c)) { num=(c-'A')/3; num = 2 + (num==8) ? 7 : num; }

Also, a note about the switch statement: The item that comes between the "case" and the ":" has to have the same type as the thing specified by the "switch()" portion. 另外,还有关于switch语句的注释:位于“ case”和“:”之间的项目必须具有与“ switch()”部分指定的事物相同的类型。 And that type must be a scalar, which excludes things like strings. 并且该类型必须是标量,其中不包括字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM