メールの内容はバイトによって分割されます


最近プロジェクトをして、長短の手紙の内容を複数のメールに分割して、バイトの160個で分割して、漢字と全角の記号の切り取りが適切でないため文字化けして、ネット上の1篇の文章を参考にして、しかしその文章はあまり周到ではありませんて、だから私は局部のコードを修正して、最後にやっと私の要した効果を完成して、最初は正則の表現式を考慮したことがあって、JAVAは支持があって、ただ、効率は私ほどではないと思います.皆さんも別の方法で実現してみてください.以下のコードはC++を適用します.

package cn.gzjp.crbt.common.util;

import java.io.UnsupportedEncodingException;

/**
*
* : ,
*


*


*
* @author zhangjh :2010-12-22
* @author :2010-12-22
* @since zte_crbt_bi
*/
public class SplitString {
private String str;
private int bytes;
private byte[] strBytes;
private byte[] result;
private byte[] another;
// 127,
private byte border = 0;

public SplitString(String str, int bytes) {
try {
this.str = str;
byte[] s = str.getBytes("GBK");
if(s.length this.bytes = s.length;
else
this.bytes = bytes;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//System.out.println("The String is: " + str + " ; Bytes is : " + bytes);
}

public String split() {
try {
strBytes = str.getBytes("GBK");
//System.out.println("strBytes.length:"+strBytes.length+",bytes:"+bytes);
result = new byte[bytes];
another = new byte[bytes - 1];
boolean flag = false;
int icount =0;
for (int i = 0; i < result.length; i++) {
if (strBytes[i] < 0) {
if (icount % 2 == 0) {
flag = true;
} else {
flag = false;
}
icount++;
}
result[i] = strBytes[i];
}
//System.out.println("flag:"+flag);
// ( >127; <0, !)
if (flag && result[result.length - 1] < border) {
if (!flag &&result[result.length - 2] < border) {
//System.out.println("1."+new String(result,"GBK"));
return new String(result,"GBK");
}
for (int i = 0; i < another.length; i++) {
another[i] = result[i];
}
//System.out.println("2."+new String(another,"GBK"));
return new String(another,"GBK");
} else {
//System.out.println("3."+new String(result,"GBK"));
return new String(result,"GBK");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static void main(String[] args) throws UnsupportedEncodingException {
long startTime =System.currentTimeMillis();
SplitString amao;
String str = "¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds¥##,ABC DEFsds";
int start=0,end=0;
int index=0;
while(str.length()>0){
amao = new SplitString(str, 160);
String ll = amao.split();
byte[] bytes = ll.getBytes("GBK");
//System.out.println(bytes.length+":"+ll);
start = ll.length();
end = str.length();
str = str.substring(start,end);
System.out.println(index+","+ll);
index++;
}
System.out.println("use time:"+(System.currentTimeMillis()-startTime));
}
}


結果:
0,¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,A
1,BC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds¥#,ABC漢DEFsds
use time:1