`

按字节数截取包含中文字符串

J# 
阅读更多
字符串截取:
有这么一串字符串,“我abc爱ce你ef”要求你写一段程序,当输入4的时候得到的子串是“我ab”
当输入6的时候得到的子串为“我abc爱”不能出现“爱”字为半边。

/**
     * 截取字符串,最后如果是半个中文,补上剩下的半个
     * <功能详细描述>
     * @param str 原始的字符串
     * @param size 需要截取的长度
     * @return 截取后的字符串
     * @see [类、类#方法、类#成员]
     */
    public static String subStringMore(String str, int size)
    {
        byte[] bb = null;
        StringBuilder sb = new StringBuilder();
        String temp = "";
        int count = 0;
        for (int j = 0; j < str.length(); j++)
        {
            temp = str.substring(j, j + 1);
            sb.append(temp);
            count += temp.getBytes().length;
            if (count >= size)
            {
                break;
            }
        }
        return sb.toString();
    }
    
    /**
     * 截取字符串,最后如果是半个中文,舍掉最后的半个
     * <功能详细描述>
     * @param str 原始的字符串
     * @param size 需要截取的长度
     * @return 截取后的字符串
     * @see [类、类#方法、类#成员]
     */
    public static String subStringLess(String str, int size)
    {
        byte[] bb = null;
        StringBuilder sb = new StringBuilder();
        String temp = "";
        int count = 0;
        int nextLength = 0;
        for (int j = 0; j < str.length(); j++)
        {
            temp = str.substring(j, j + 1);
            sb.append(temp);
            count += temp.getBytes().length;
            if (count >= size)
            {
                break;
            }
        }
        if (count > size)
        {
            return sb.substring(0, sb.length() - 1);
        }
        else
        {
            return sb.toString();
        }
    }

 

0
0
分享到:
评论
1 楼 phenom 2009-09-28  
substring无论如何都得不到半个字,所以结论是错的.

相关推荐

Global site tag (gtag.js) - Google Analytics