[英]How to loop a switch statement while using StringBuilder?
My current set of switch statements work, but they take up far too many lines and I am unsure of how to create a working loop to condense the switch statements. 我当前的switch语句集可以工作,但是它们占用了太多行,而且我不确定如何创建工作循环来压缩switch语句。
Here is my current switch statement within a method (I have six, the following are incremented by 1) 这是我当前在一个方法中的switch语句(我有六个,以下加1)
public static String convert (String str) {
String strb = new StringBuilder(str);
switch (str.charAt(4)) {
case 'a':
case 'b':
case 'c':
strb.insert(4, 2);
strb.deleteCharAt(5);
break;
case 'd':
case 'e':
case 'f':
strb.insert(4, 3);
strb.deleteCharAt(5);
break;
case 'g':
case 'h':
case 'i':
strb.insert(4, 4);
strb.deleteCharAt(5);
break;
case 'j':
case 'k':
case 'l':
strb.insert(4, 5);
strb.deleteCharAt(5);
break;
case 'm':
case 'n':
case 'o':
strb.insert(4, 6);
strb.deleteCharAt(5);
break;
case 'p':
case 'q':
case 'r':
case 's':
strb.insert(4, 7);
strb.deleteCharAt(5);
break;
case 't':
case 'u':
case 'v':
strb.insert(4, 8);
strb.deleteCharAt(5);
break;
case 'w':
case 'x':
case 'y':
case 'z':
strb.insert(4, 9);
strb.deleteCharAt(5);
break;
}
return strb.toString();
}
I have tried a for loop, but it does not seem to work. 我已经尝试过for循环,但是它似乎不起作用。 Any suggestions? 有什么建议么?
for (index = 4; index < str.length(); index++) {
switch (str.charAt(index)) {
case 'a':
case 'b':
case 'c':
strb.insert(index, 2);
strb.deleteCharAt(index + 1);
break;
case 'd':
case 'e':
case 'f':
strb.insert(index, 3);
strb.deleteCharAt(index + 1);
break;
case 'g':
case 'h':
case 'i':
strb.insert(index, 4);
strb.deleteCharAt(index + 1);
break;
case 'j':
case 'k':
case 'l':
strb.insert(index, 5);
strb.deleteCharAt(index + 1);
break;
case 'm':
case 'n':
case 'o':
strb.insert(index, 6);
strb.deleteCharAt(index + 1);
break;
case 'p':
case 'q':
case 'r':
case 's':
strb.insert(index, 7);
strb.deleteCharAt(index + 1);
break;
case 't':
case 'u':
case 'v':
strb.insert(index, 8);
strb.deleteCharAt(index + 1);
break;
case 'w':
case 'x':
case 'y':
case 'z':
strb.insert(index, 9);
strb.deleteCharAt(index + 1);
break;
}
}
A better approach is to remove the switch
statement altogether, and use a lookup table to select the digit: 更好的方法是完全删除switch
语句,并使用查找表选择数字:
private static final String DIGIT_LOOKUP = "22233344455566677778889999";
...
int pos = Character.toLowerCase(str.charAt(index)) - 'a';
char digit = DIGIT_LOOKUP.charAt(pos);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.