java截取指定长度字符串,字符串包含中文

该篇文章介绍了如何使用Java编写一个名为`cutStringByLen`的方法,用于在GBK编码下截断字符串,确保不超过40个字符,同时处理中文标点和空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.UnsupportedEncodingException;


public class test {
    public static String cutStringByLen(String s,int maxLength) throws UnsupportedEncodingException{
        //返回值赋值
        String rs = "";
        //判断为空或者小于40直接返回原来字符串
        if(s.isEmpty() || s.getBytes("GBK").length<40) {
            System.out.println("实际最大可返回长度:"+s.getBytes("GBK").length);
            return s;
        }
        //去掉空格
        //s = s.replaceAll(" ","");
        //转换成char数组
        char[] charArray = s.toCharArray();
        //长度计数初始化
        int count = 0;
        for(char ch : charArray) {
            //将char转换为string并获取长度,字符指定GBK
            int length = String.valueOf(ch).getBytes("GBK").length;
            //存储当前返回值,用于返回超过40个字符且不等于40个字符情况
            String tempRs = rs;
            //拼接返回值
            rs = rs + ch;
            //存储当前计算长度之前的长度,用于返回超过40个字符且不等于40个字符情况
            int countBefor = count;
            //累加长度
            count = count + length;
            if(count == maxLength) {
                break;
            }
            if(count>maxLength) {
                //maxLength = countBefor;
                rs = tempRs;
                break;
            }
        }
        System.out.println("实际最大可返回长度:"+ maxLength);
        return rs;
    }

    //测试
    public static void main(String[] args) throws UnsupportedEncodingException {
        //超过40字符,且存在中文标点和空格,其他符号
        String s ="匹电宝,匹电宝 - 比喻框架盛祥-胡能!及!图2皮把3司";
        String s1 = "匹电宝,匹电宝 - 公用事业缴111-湘普!人!";
        String s2 ="匹电宝,匹电宝 - 公用规划时皮-湘22!!";
        System.out.println("超过40字符,且存在中文标点和空格,其他符号:" +  cutStringByLen(s,40));
        System.out.println("等于40字符,且存在中文标点和空格,其他符号:" +  cutStringByLen(s1,40));
        System.out.println("小于40字符,且存在中文标点和空格,其他符号:" +  cutStringByLen(s2,40));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值