日期:2014-05-16  浏览次数:20402 次

JSP 替换字符串的实现
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.util.StringTokenizer" %>
<!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>
<style type="text/css">
<!--
.STYLE1{
   font-size:large;
}
-->
</style>
<script>
function checkForm(){
if(document.form1.str==""){
alert("原字符串不能为空!");
return false;
}
if(document.form1.old==""){
alert("查找字符串不能为空");
return false;
}
}
</script>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String str=request.getParameter("str");
if(str==null)
str="";
String old=request.getParameter("old");
if(old==null)
old="";
String replacement=request.getParameter("replacement");
if(replacement==null)
replacement="";

%>
<form name="form1" action="replace.jsp" method="post">
<div class="STYLE1">替换字符串中指定的字符</div>
原字符串<input type="text" name="str" value="<%=str %>">
<br  />
查找<input type="text" name="old" value="<%=old %>">
<br  />
替换<input type="text" name="replacement" value="<%=replacement %>"/>
<hr  />
<input name="ok"  type="submit" value="替换">

</form>
<p>
<%
StringBuffer buf=new  StringBuffer();
int  index=-1;
while(!str.equals("")&&!old.equals("")&&(index=str.indexOf(old))!=-1){
buf.append(str.substring(0,index));
buf.append(replacement);
str=str.substring(index+old.length());
}
buf.append(str);
out.print(buf.toString());
%>
</p>
</body>
</html>