计算字符串的实际长度

配合使用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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值