关于中文字符输出的问题

jack_wub 2009-12-10 11:54:44
有一列字符串,如String s=“说sg收a”有7个字节,中文占二个字节。
将该列字符按每行有相应的字符输出,如果某一行的最后的一个字符的中文被拆开,则将其放在下一行输出。
如:String s="收sds到sfq都是sk是";按每行6个字符输出的话:则结果为:
第一行为:收sds
第二行为:到sfq
第三行为:都是sk
第四行为:是

...全文
196 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
abuying 2010-09-15
  • 打赏
  • 举报
回复
可怜当时没做出来啊。
whut0802 2009-12-12
  • 打赏
  • 举报
回复
呵呵,面试的题目啊,一时好像是搞不定
whut0802 2009-12-11
  • 打赏
  • 举报
回复
把昨天晚上的代码改了下,可以满足你的要求了

public class TestString {
public int getTotalByte(char[] c) {
int totalBytes = 0;
for (int i = 0; i < c.length; i++) {
if (c[i] > 255) {
totalBytes = totalBytes + 2;
}
if (c[i] < 255) {
totalBytes = totalBytes + 1;
}
}
return totalBytes;
}

public void outputString(String str, int i) {
int count = 0;
StringBuffer sb = new StringBuffer();
char[] c = str.toCharArray();
int totalbytes = getTotalByte(c);
if (i <= totalbytes) {
for (int j = 0; j < i; j++) {
if (c[j] > 255 && (i - count) > 1) {
count = count + 2;
sb.append(c[j]);
} else if (c[j] < 255 && (i - count) > 0) {
count = count + 1;
sb.append(c[j]);
} else
break;
}
System.out.println(sb);
int index = sb.length();
outputString(str.substring(index), i);
}
if(i>totalbytes){ //避免数组越界的判断
System.out.println(str);
}
}

public static void main(String[] args) {
TestString ts = new TestString();
ts.outputString("收sds到sfq都是sk是", 6);
System.out.println("-------------------------------");
ts.outputString("收sds到sfq都是sk是", 5);
System.out.println("-------------------------------");
ts.outputString("收sds到sfq都是sk是", 7);
}
}
beiouwolf 2009-12-11
  • 打赏
  • 举报
回复
哦 看错了 还要判断中文换行阿
beiouwolf 2009-12-11
  • 打赏
  • 举报
回复

String s = "收sds到sfq都是sk是";

Pattern p = Pattern.compile("([\\u4e00-\\u9fa5]+[\\w]*)");
Matcher m = p.matcher(s);

while(m.find()) {
System.out.println(m.group());
}
jack_wub 2009-12-11
  • 打赏
  • 举报
回复
这是我在面试的时候碰到的问题,当时没有搞出来,呵呵....
whut0802 2009-12-11
  • 打赏
  • 举报
回复
坏了,递归到最后可能会数组越界。。。明天再看吧
whut0802 2009-12-11
  • 打赏
  • 举报
回复
这个题目有点叼。。。

public class TestString {
public void outputString(String str,int i){
int count=0;
StringBuffer sb=new StringBuffer("");
char[] c=str.toCharArray();
if(i==0){
System.out.println(str);
}
if(i==1&&c[0]>255){
System.out.println("第一个字符是汉字,无法分割");
System.exit(0);
}
else{
for(int j=0;j<i;j++){
if(c[j]>255&&(i-count)>1){
count=count+2;
sb.append(c[j]);
}
else if(c[j]<255&&(i-count)>0){
count=count+1;
sb.append(c[j]);
}
else break;
}
}
System.out.println(sb);
int index=sb.length();
outputString(str.substring(index), i);
}
public static void main(String[] args){
TestString ts=new TestString();
ts.outputString("收sds到sfq都是sk是",6);
}
}

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧