zoukankan      html  css  js  c++  java
  • java 字符串截取

    截取指定长度的字符串,如果超出就用more的内容来替换
     截取的字节数,截取的时候,有可能会少截取一位(当最后一位是1个双字节的话,会少截取一个)

    public class Test {
        public static void main(String[] args) {
            String s="a测试bcd试1";
            System.err.println(subAndReplaceString(s, 50, "..."));
        }
        
        public static String subAndReplaceString(String str, int toCount, String more) {
            int reInt = 0;
            String reStr = "";
            if (str == null)
                return "";
            char[] tempChar = str.toCharArray();
            for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
                String s1 = String.valueOf(tempChar[kk]);
                byte[] b = s1.getBytes();
                reInt += b.length;
                if (reInt > toCount)
                    break;
                reStr += tempChar[kk];
            }
            if (toCount == reInt || (toCount == reInt - 1))
                reStr += more;
            return reStr;
        }
    }

  • 相关阅读:
    OpenStack(M版)之基础环境配置(2 更换源、安装OpenStack客户端)
    OpenStack(M版)之基础环境配置(1静态ip、网络接口)
    Java关于print、println、printf的区别
    输出1-n的全排列dfs
    统计难题
    单词数
    减肥计划
    Zero Array---思维题
    快速幂+快速乘
    线段树求逆序对
  • 原文地址:https://www.cnblogs.com/Snowflake/p/3412216.html
Copyright © 2011-2022 走看看