Title: Write a function that intercepts the string, input as a string and byte number, and output as a byte-truncated string. But to ensure that the Chinese character is not truncated half, such as "I abc" 4, should be truncated to "I ab", input "my ABC-def", 6, should be exported as "my ABC" instead of "I abc+ Han half."
Requirements Analysis:
1. Input as a string and byte number, output as byte-truncated string--------------"intercept the operation string by byte [byte], first convert string to byte type
.2, Chinese characters can not be cut half---------------------------------------------------------------------------------------------------------- When the Chinese character is truncated, the ASC code of the corresponding byte is less than 0.
Second, technical difficulties
1, know the Chinese character intercept the corresponding byte of the ASC code is less than 0 of the value
2, the string operation should have to face a problem, whether the string is valid null, the length of the string 0,1 this boundary processing code implementation:
<pre name= "code" class= "Java" >package cn.itcast;
/**
* Write a function to intercept a string, enter a string and byte number, output as a byte-truncated string
* But ensure that the Chinese character is not truncated half.
* @author Lenovo
* * *
/public class Splitspring {public
static void Main (string[] args) {
String str1 = "I abc";
String str2 = "I abc han def";
Splitstring (str1,4);
Splitstring (str2,9);
}
public static void Splitstring (string str, int len) {
if (null = = str) {
System.out.println ("The string is null"); return
;
}
int bytenum = 0;
byte[] bt = Str.getbytes ();
Bytenum = bt.length;
if (Len > Bytenum) {
len = bytenum;
}
if (bt[len]<0) {
str = new String (bt,0,--len);
System.out.println (str);
else{
str = new String (Bt,0,len);
System.out.println (str);}}
Processing results:
I ab
i i abc Han de