省略显示长字符串

来源:互联网 发布:剑灵捏脸数据免费 编辑:程序博客网 时间:2024/05/01 00:18

      我们在许多网站的页面都可以看到省略长字符串的情况,如在网站的首页上显示出一些文章的标题,然而这些文章的标题有长有短,如果HTML表格固定列宽,则文章的标题过长时就会自动换行显示,如果没有固定列宽就会把显示内容变得杂乱无章,甚至使页面变形。通常的做法是,截取标题字符串的前面一部分,然后在后面加“...”。下面给出一个具体的简单的示例。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'strTruncate.jsp' starting page</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"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body><%!public static String strTruncate(String source, int len, String delim) {/*source:需要截取的字符串 ,  len: 要截取的字节数, delim: 截取后附加在后的字符串  */if (source == null)return null;   //字符串为空不作处理 int start, stop, byteLen; int alen = source.getBytes().length;  // 得到需要截取的字符串的字节数 if (len > 0) {if (alen <= len)return source; //如果比要截取的字节数还小,则不作处理 start = stop = byteLen = 0;while (byteLen <= len) {if (source.substring(stop, stop + 1).getBytes().length == 1) {//单字节字符处理 byteLen += 1;} else {   //双字节字符处理 byteLen += 2;}stop++;}StringBuffer sb = new StringBuffer(source.subSequence(start,stop - 1));if (alen > len)sb.append(delim); //加入附加在后的字符串 return sb.toString();}return source;}%><%String s1 = new String("20130227_attach_22706_重庆邮电大学关于做好2013届毕业学生毕业资格预审工作的通知");String s2 = new String("20130226_attach_2121_知识守护生命——重庆邮电大学救护技能培训班招生简章(春季)");String s3 = new String("重庆邮电大学2012-2013学年第二学期开学教学相关工作安排通知");out.println("长字符串截取示例:<br> ");out.println(strTruncate(s1, 40, "......") + "<br>");out.println(strTruncate(s2, 40, "...... ") + "<br>");out.println(strTruncate(s3, 40, "...... ") + "<br>");%></body></html>


 运行结果
注:本文摘选邓子云的JSP网络编程。。。

	
				
		
原创粉丝点击