把手机键盘输入转化成短消息 [No. 52]

手机键盘每个数字对应的字符如下:

0 ---> "0";

1 ---> "1";

2 --- >"ABC2";

3 --->"DEF3";

4 --->"GHI4";

5 --->"JKL5";

6 --->"MNO6";

7 --->"PQRS7";

8 --->"TUV8";

9 --->"WXYZ9";

* ---> 空格;

# ---> 断开;

比如,输入为

222 ---> C,

222222 ---> B

22233 ---> CE

222#33 ---> CE

222*33 ---> C E

2#3*4*4 ---> AD G G

问题:

现在给你一串字符输入,把它转化成为短消息内容。

分析:

其实,这个问题只需要对三种情况进行处理:当字符为 #, 当字符为 * 或者前后字符不一样的时候。只是处理的时候,需要小心,要注意一些特殊情况,比如特殊字符在前面:###33,最后一个是特殊字符:3*** 等。

public class PhonePad {
	public static final String[] keypad = {"0", "1", "ABC2", "DEF3", "GHI4", "JKL5", "MNO6", "PQRS7", "TUV8", "WXYZ9"};
	
	public static String translate(String input) {
		if (input == null || input.length() == 0 || input.equals("*") || input.equals("#")) return "";
		
		int start = 0; 	
		char preChar = ' '; //previous character
		char curChar = ' '; //curent character
		int times = - 1;  // the number of times a specific character appears continuously
		int value = -1;  
		int length = -1; // the length of a digit. i.e., the length of digit 5: "JKL5" is 4
		String msg = "";
		
		while (start < input.length()) {
			curChar = input.charAt(start);
			if (curChar == '#' || curChar == '*' || (curChar != preChar && times != -1)) {
				// deal with case that '#' and '*' appear continuously
				if (curChar == '#' && times == -1) {
					start++;
					continue;
				}
				if (curChar == '*' && times == -1) {
					msg = msg + " ";
					start++;
					continue;
				}
				value = preChar - '0';
				length = keypad[value].length();
				times = times % length; // the position of character
				msg = msg + String.valueOf(keypad[value].charAt(times));
				if (curChar == '*') {
					msg = msg + " ";
				}
				
				if (curChar >= '0' && curChar <= '9') {
					times = 0;
					preChar = curChar;
				} else {
					times = -1;
				}
			} else {
				preChar = curChar;
				times++;
			}
			start++;
		}
		//deal with the last character
		if (times != -1) {		
			value = curChar - '0';
			length = keypad[value].length();
			times = times % length;
			msg = msg + String.valueOf(keypad[value].charAt(times));
		}
		return msg;
	}
	
	public static void main(String[] args) {
		System.out.println(PhonePad.translate("##*2#211**2*"));
	}
}
转载请注明出处: http://blog.csdn.net/beiyeqingteng

你可能感兴趣的:(把手机键盘输入转化成短消息 [No. 52])