编程面试题二

方法一!

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);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值