頁面使用時:
<s:bean name="com.hwtt.rbt.user.bean.CutStringBean" id="cutString"> <s:param name="str" value="singerName"/> <s:param name="hold" value="3"/> <s:property value="formatStr"/></s:bean>
工具類:
public class CutStringBean { private String str;//要格式化的字串 private int hold;//保留的長度 private String end;//結束符 private String formatStr;//格式化後的字串 private static final String END = ".."; public CutStringBean() { } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public int getHold() { return hold; } public void setHold(int hold) { this.hold = hold; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public String getFormatStr() { formatStr = getShortStr(str, hold, end); return formatStr; } public void setFormatStr(String formatStr) { this.formatStr = formatStr; } /** * 將字串縮短到指定長度,且與結束符結束 * * @param str * @param hold 保留的長度 * @param end 結束字串,為空白則為“..” * @return String */ public String getShortStr(String str, int hold, String end) { if (str == null || hold < 1) return ""; str = str.trim(); if (hold > str.length()) return str;// int length = (hold % 2) != 0 ? hold - 1 : hold; end = end == null ? END : end; int abc123Size=0;//數字和字母個數 if (str.length() > hold){ for(int i=0;i<hold;i++){ if(java.util.regex.Pattern.matches("[a-zA-Z0-9]",""+str.charAt(i))){ //判斷數字或字母時增1 abc123Size++; } } int tempHold = hold; int twoAbc123=0; for(int i=tempHold;i<tempHold+abc123Size && i<str.length();i++){ if(java.util.regex.Pattern.matches("[a-zA-Z0-9]",""+str.charAt(i))){ //如果是數字或字母時間長度度增1 hold++; }else if(twoAbc123 == 1){//一個中文需要兩個數字或字母 hold++; twoAbc123=0; }else{ twoAbc123++; } } return hold >= str.length() ? str : str.substring(0, hold) + end; } return str; }}