zoukankan      html  css  js  c++  java
  • JSP-简单的练习省略显示长字符串

    <%@ page contentType="text/html; charset=gb2312" %>  <!-- JSP指令标签 -->
    <%@ page import="java.util.*" %>   <!-- JSP指令标签 -->
    <html>
    <head>
    <title>长字符串截取演示样例</title>
    </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.substring(start,stop-1));
                       if(alen>len)
                       {// 增加附加在后的字符串
                            sb.append(delim);
                       }
                       return sb.toString();
                  }
                  return source;
             }
          %>
          
          <%
              String s1=new String("aaaaaaaaaaaaaaaa");
              String s2=new String("bbbbbbbbbbbbbbbbbbb");
              String s3=new String("cccccccccccccccccccccc");
              out.println("长字符串截取演示样例<br>");
              out.println(strTruncate(s1,10,"...")+"<br>");
              out.println(strTruncate(s2,5,"...")+"<br>");
              out.println(strTruncate(s3,6,"...")+"<br>");
           %>
    </body>
    </html>

    当中,strTruncate用来截取字符串,并用指定的字符串附加到处理完后的字符串的末尾。

    执行结果如图:


    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    将Excel表中的数据导入到数据库
    别人面试的学习路线
    和同门一起做的PHP网站
    正则表达式
    python 编码形式简单入门
    游戏开发者面临的几大问题
    quick-cocos2d-x与 cocos2d-x的关系
    cocos2dx中的坐标系统
    重载new和delete来检测内存泄漏
    VS下使用Google Protobuf完成SOCKET通信
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4885573.html
Copyright © 2011-2022 走看看