配合使用toCharArray方法和getBytes方法,首先使用toCharArray方法将一个字符串转换成字符数组,然后循环这个字符数组,将每个字符通过getBytes方法转换成字节数组并获取字节数组长度,最后累计每个字符的长度,获得长度
创建StringUtil的JavaBean类,该类中提供的方法用于获得字符串的实际长度
package com.cn.zj.bean;
public class StringUtil2 {
private String str; //需要计算长度的字符串
private int strLength; //字符长度
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public void setStrLength(int strLength) {
this.strLength = strLength;
}
public int getStrLength(){
char[] c=str.toCharArray();
int factualLength=0;
for(int i=0;i<c.length;i++){
factualLength=String.valueOf(c[i]).getBytes().length;
if(factualLength==3){
factualLength=2;
}
strLength+=factualLength;
}
return strLength;
}
}
创建index.jsp页面,包含一个提交字符串信息的表单
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="getlength.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>
</tr>
</table>
</form>
</body>
</html>
创建getlength.jsp页面,该页中首先获得表单中的字符串,然后调用StringUtil类的方法计算字符串的长度
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>处理页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<style type="text/css">
table{
border: 1px solid;
border-color: green;
color: gray;
font-size: 12px;
}
</style>
</head>
<body>
<%
String str = request.getParameter("str");
%>
<jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtil2"></jsp:useBean>
<jsp:setProperty property="str" name="strBean" value="<%=str %>"/>
<table >
<tr>
<td>字符串:</td>
<td align="left">
<jsp:getProperty property="str" name="strBean"/>
</td>
</tr>
<tr>
<td>实际长度:</td>
<td>
<jsp:getProperty property="strLength" name="strBean"/>
</td>
</tr>
</table>
</body>
</html>