Question:
* Set the phone number to One two... Nine zero is translated into 1 2 .. 9 0
*
* Double exists in the middle.
*
* For example
* Input: onetwothree
* Output: 123
* Input: onetwodoubletwo
* Output: 1222
* Input: 1two2
* Output: Error
* Input: doubledoubletwo
* Output: Error
Analysis: a good method for string operations is replaceall (). With this method, we can easily translate English into numbers, and the rest is to identify illegal problems, this can be a regular expression, but please forgive the regular expression of the landlord slag (the landlord will definitely make a bad complement regular expression later). Thank you!
The Code is as follows:
Package com. wenj. test;
Import java. util. RegEx. matcher;
Import java. util. RegEx. pattern;
/**
*
* @ Author wenj91-PC
*
*/
Public class testtranslatetelnum {
Public static void main (string ARGs []) {
String strin = "onetwodoubletwo ";
Testtranslatetelnum TT = new testtranslatetelnum ();
System. Out. println (TT. translatetelnum (strin ));
}
Public String translatetelnum (string strin ){
String strtemp = strin;
String [] strarr = {"one", "two", "three", "four", "five", "Six", "Seven", "eight ", "Nine", "zero", "double "};
String [] strnum = {"1", "2", "3", "4", "5", "6", "7", "8 ", "9", "0 ","#"};
Pattern P = pattern. compile ("\ doubledouble | \ d | \ P {punct}"); // If double/[0-9]/other characters exist, an error is returned directly.
Matcher M = P. matcher (strtemp );
If (M. Find ()){
Return "error ";
}
For (INT I = 0; I <strarr. length; I ++ ){
Strtemp = strtemp. replaceall (strarr [I], strnum [I]);
}
Char [] SC = strtemp. tochararray (); // This is added later. Fix the previous problems.
For (INT I = 0; I <SC. length; I ++ ){
If ('#' = SC [I]) {
If (I = SC. Length-1) // If double is at the end, it is also incorrect.
Return "error ";
SC [I] = SC [I + 1]; // replace double with the number modified by double.
}
}
Strtemp = ""; // stringbuffer is recommended here
For (INT I = 0; I <SC. length; I ++ ){
Strtemp + = SC [I];
}
P = pattern. Compile ("[A-Za-Z]"); // If [A-Za-Z] still exists, it indicates that the input is incorrect and an error is returned.
M = P. matcher (strtemp );
If (M. Find ()){
System. Out. println (strtemp );
Return "error ";
}
Return strtemp;
}
}