首页 arrow J2ME开发 arrow 新手上路 arrow J2ME 根据显示宽度分割字符串
J2ME 根据显示宽度分割字符串
Author Author: Wupei | Date Date: 2009-03-14 | View Count View: 2626 | Section & Category J2ME开发 - 新手上路 | Digg Digg: 4

经常需要的一个功能就是根据显示区域的宽度将一个较长的字符串

分割成为一个字符串数组用于显示,以下是实现代码,希望对大家有帮助,如果有什么错误

请不吝赐教。

/**
 * 将一个长字符串根据指定宽度和字体分割成字符串数组
 *
 * @param longString
 *            用于分割的较长字符串
 * @param font
 *            用于测量字符串宽度的字体
 * @param width
 *            显示设备上单行字符串的宽度
 * @return 分割成的字符串数组
 */
private String[] splitLongStringIntoStringArray(String longString,
                                                Font font, int width) {
    if (font.stringWidth(longString) <= width) {
        return new String[] {longString};
    } else {
        int stringLength = longString.length();
        char[] chars = longString.toCharArray();
        Vector v = new Vector();
        int offset = 0, length = 1;
        while (offset + length < stringLength) {
            if (font.charsWidth(chars, offset, length) < width) {
                length++;
            } else {
                v.addElement(longString.substring(offset, offset + length));
                offset = offset + length;
                length = 1;
            }
        }
        if (offset < stringLength) {
            v.addElement(longString.substring(offset));
        }
        String[] strings = new String[v.size()];
        v.copyInto(strings);
        return strings;
    }
}

更多阅读:

 
   评论 (1)
评论的 RSS
1
by: 小宗 (注册会员) 2010-04-15 14:12
:) 谢谢分享 正在学习
回复该评论
查看2条回复

我要发表评论

登录菜单

最新文章

本月热门

订阅本站

RSS 0.91 RSS 1.0 RSS 2.0 ATOM 0.3 OPML