String.substring(0,200)
以及解决其中的全角半角问题
http://www.jspcn.net/htmlnews/11049388356561897.html
我是这样解决全角半角问题的 |
作者:未知 文章来源:www.jspcn.net 访问次数: name="ad" src="../count.jsp?news_id=2646" frameborder="0" width="30" scrolling="no" height="10">次 加入时间:2005-01-19 |
|
从数据库里面读取到数据,想显示前100个字,考虑用String.substring(0,200); 但是如果这100个字里面 有半角的字(比如1,a等),就麻烦了。
我是这样解决全角半角问题的。 写一个toGB(String str)函数,如果toGB(String str)里面的str不能正常转化成 gb2312的字符串, 那么显示为空白,toGB(String str).length()为0 假如想返回前100个字, 这样就可以考虑用toGB(String.substring(0,200)); 然后判断toGB().length()是否是0,如果是0,则substring(0,200-1);
<% //-------整个程序如下---------%> <%!public static String toGB(String str){
try{ str=new String(str.getBytes("ISO8859_1"),("GB2312")); return str; } catch(Exception e){ return null; } }
//-----------------------------------------------------------------
//....... //和数据库的连接 //.......
String content;
content=rs.getString("content");
int Ccount; if((Ccount=content.length())>200){ Ccount=200; } if(toGB(content.substring(0,Ccount)).length()==0){ content=content.substring(0,Ccount-1); }else{ content=content.substring(0,Ccount); }
out.print(toGB(content)); %>
| |