Java programming interview questions, used for a moment.
Question:
Compile a function to intercept a string. The input is a string and number of characters, and the output is a string truncated by bytes.
However, to ensure that no half of Chinese characters are cut, for example, "my ABC" 4, it should be cut to "my AB ",
Input "I abc Han Def", 6, should be output as "I abc" instead of "I ABC + Han half ".
Public class splitstring
...{
Public void split (string S, int Len)
...{
String result = "";
Int counter = 0, I = 0;
Char temp;
While (counter <Len)
...{
Temp = S. charat (I );
If (character. getnumericvalue (temp )! =-1)
...{
Result = Result + temp;
Counter ++;
I ++;
}
Else
...{
Result = Result + temp;
Counter = counter + 2;
I ++;
}
}
If (counter> Len) // remove the remaining half of the Chinese bytes
...{
If (LEN = 1)
...{
Result = "";
}
Else ...{
Result = result. substring (0, counter-3 );
}
}
System. Out. println (result );
}
Public splitstring ()
...{}
Public static void main (string [] ARGs)
...{
Splitstring test = new splitstring ();
String A = "My ABCD ";
Test. Split (A, 3 );
}
}