方法一!
import java.io.IOException;
import java.io.UnsupportedEncodingException;public class subStringdemo1 {
/**
* 有一列字符串,如String s=“说sg收a”有7个字节,中文占二个字节。
将该列字符按每行有相应的字符输出,如果某一行的最后的一个字符的中文被拆开,则将其放在下一行输出。
如:String s="收sds到sfq都是sk是";按每行6个字符输出的话:则结果为:
第一行为:收sds
第二行为:到sfq
第三行为:都是sk
第四行为:是
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String s="收sds到sfq都是sk是";
subStringdemo1.doString(s, 6);
}
public static int totalbyte(String s) throws IOException{
return s.getBytes("GBK").length;
}
public static void doString(String s, int m) throws Exception{
int count = 0;
StringBuffer sb = new StringBuffer();
if(m<subStringdemo1.totalbyte(s)){
char[] c = s.toCharArray();
for(int i=0; i<m; i++){
if(c[i]>255 && (m-count)>1){
count+=2;
sb.append(c[i]);
}else if(c[i]<255 && (m-count)>0){
count+=1;
sb.append(c[i]);
}else {
break;
}
}
System.out.println(sb);
int len = sb.length();
doString(s.substring(len), m);
}else {
System.out.println(s);
}
}
}
方法二!
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class subStringdemo {
/**
有一列字符串,如String s=“说sg收a”有7个字节,中文占二个字节。
将该列字符按每行有相应的字符输出,如果某一行的最后的一个字符的中文被拆开,则将其放在下一行输出。
如:String s="收sds到sfq都是sk是";按每行6个字符输出的话:则结果为:
第一行为:收sds
第二行为:到sfq
第三行为:都是sk
第四行为:是
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String s = "收我sds到sfq都是sk是";
doString(s,3);
}
public static boolean isCheinese(char c) throws IOException{
return String.valueOf(c).getBytes("GBK").length >1;
}
public static int totalbyte(String s) throws Exception{
int b = s.getBytes("GBK").length;
return b;
}
public static void doString(String s, int m) throws Exception{
if(m <= s.length()){
String ss = new String(s.getBytes(),"GBK");
StringBuffer sb = new StringBuffer();
int temp = 0;
for(int i =0; i<m; i++){
char c = ss.charAt(i);
if(subStringdemo.isCheinese(c)){
temp+=2;
}else {
temp +=1;
}
if(temp <= m){
sb.append(c);
}
}
String sb1 = sb.toString();
System.out.println(sb1);
String sss = ss.substring(sb1.length());
//System.out.println("----->>"+sss);
//System.out.println(sss.getBytes().length);
doString(sss,m);
}else if( m<subStringdemo.totalbyte(s)){
int temp = 0;
StringBuffer sb = new StringBuffer();
for(int i =0; i<s.length(); i++){
char c = s.charAt(i);
if(subStringdemo.isCheinese(c)){
temp+=2;
}else {
temp +=1;
}
if(temp <= m){
sb.append(c);
}
}
System.out.println(sb);
System.out.println(s.substring(sb.length()));
}else{
System.out.println(s);
}
}
}