一个字符串输出问题!!!!

lirihong 2009-03-24 01:14:00
今天去了一家面试遇到一个问题,不知道该怎么样解决!请高手指点一下!谢谢
已知:一个字符串和要截的位数,然后字符串返回!但要达到这样的效果!
比如:字符串:“我ABC” 要截取4位 效果:“我AB”
字符串:“我ABC你” 要截取6位 效果:“我ABC”
不能将一个中文的汉字截取成一般 比如“我ABC”+“你”的一半!要保留整个汉字!

请兄弟们指教一下!谢谢!
...全文
94 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangbo6791644 2009-03-24
  • 打赏
  • 举报
回复
感谢你,学习了
lirihong 2009-03-24
  • 打赏
  • 举报
回复
非常感谢!学习了!结贴!
steryzone 2009-03-24
  • 打赏
  • 举报
回复
public class Cut {
public String cut(String s, int n) {
String c="";
String d = "";
String[] b = s.split("");
for (int i = 0; i < b.length; i++) {
c = c + b[i];
if((c.getBytes().length)==n){
d = d + b[i];
break;
}else if((c.getBytes().length)>n){
break;
}
d = d + b[i];
}
return d;
}

public static void main(String[] args) {
Cut cu = new Cut();
String a = cu.cut("a接口cd喊f", 4);
System.out.println(a);
}
}
shuai45 2009-03-24
  • 打赏
  • 举报
回复
public static String getString(String args,int length){
if(length>args.length())
length=args.length();
String output="";
byte[] b=args.getBytes();
if(length/2!=0){
if(b[length]<0)
length=length-1;
}
output=new String(b,0,length);
return output;
}
niuxinlong 2009-03-24
  • 打赏
  • 举报
回复
可以试试用split("")将字符串分割成数据,然后取数组的length-2个元素重新生成字符串
simpledong 2009-03-24
  • 打赏
  • 举报
回复
楼上的方法肯定是OK的
LZ放心使用吧:)
superjava_2006 2009-03-24
  • 打赏
  • 举报
回复
这个试试

public static void getChar(String str, int count) {
byte[] byteArray = new byte[count];
byte[] temp = str.getBytes();
int ii = 0;
for (int i = 0; i < count; i++) {
byteArray[i] = temp[i];
if (temp[i] < 0) {
ii++;
}
}
if (ii % 2 == 1) {
byteArray[count - 1] = ' ';
}
System.out.println(new String(byteArray).trim());

}

81,092

社区成员

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

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