StringUtil2.java
public class StringUtil2 {
private String string;//需要计算长度的字符串
private int strLength;//字符串的实际长度
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getStrLength() {
char[] c=string.toCharArray();//转为字符数组
int factualLength=0;//用于保存每个字符的实际长度
for (int i = 0; i < c.length; i++) {
factualLength=String.valueOf(c[i]).getBytes().length;//获取字节数组的长度
if (factualLength==3) {
factualLength=2;//utf-8编码的汉字实际字节长度为3,改为2
}
strLength+=factualLength;//将每个字符长度累加
}
return strLength;
}
public void setStrLength(int strLength) {
this.strLength = strLength;
}
}
index.jsp
<body>
<form action="result.jsp" method="post">
<table>
<tr height="35">
<td align="center">请输入字符串</td>
<td><input type="text" name="str"/></td>
<td align="center"><input type="submit" value="提交"/></td>
</table>
</form>
</body>
result.jsp
<body>
<%
String str=request.getParameter("str");
%>
<jsp:useBean id="strBean" class="com.count.StringUtil2"></jsp:useBean>
<jsp:setProperty property="string" name="strBean" value="<%=str %>"/>
<table>
<tr>
<td>字符串:</td>
<td align="left"><jsp:getProperty property="string" name="strBean"/>
</td>
</tr>
<tr><td>实际长度:</td>
<td><jsp:getProperty property="strLength" name="strBean"/>
</td>
</tr>
</table>
</body>
26.PNG
27.PNG
28.PNG
网友评论