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用来截取字符串,并用指定的字符串附加到处理完后的字符串的末尾。

    执行结果如图:


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

  • 相关阅读:
    旅行计划(拓扑排序)
    Extended traffic
    Tram(最短路)
    Cow and Friend(贪心)
    Invitation Cards(SPFA + 反向建边)
    Johnny and Another Rating Drop(找规律)
    python连接服务器上传文件,后台执行命令
    linux杀死某个进程
    linux安装杀毒软件
    django项目同一用户不能同时登陆
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4885573.html
Copyright © 2011-2022 走看看