转换输入文本中的回车和空格
生活随笔
收集整理的這篇文章主要介紹了
转换输入文本中的回车和空格
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
主要應用String類中的replaceAll()方法,將用戶輸入的空格和回車替換成HTML代碼中的
和 ,該方法用于將字符串中的某個子字符串替換成指定的字符串:
新建StringUtil的JavaBean類,該類主要包含一個轉換空格和換行符的方法
package com.cn.zj.bean; public class StringUtiil1 {private String str; //要替換的字符串public void setStr(String str){this.str = str;}public String getStr(){return replace(str);}/*** 替換字符串的方法* @param str:源字符串* @return 替換后的字符串*/public String replace(String str){String newStr1="";String newStr2="";newStr1 = str.replaceAll(" ", " "); //替換字符串中的空格為" "newStr2 = newStr1.replaceAll("\r\n", "<br>"); //替換換行符為"<br>"return newStr2; //返回替換后的字符串} }創建index.jsp頁面,用于在表單中輸入文本
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!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> </head> <body> <form action="replace.jsp" method="post"><table><tr><td align="center">請輸入信息</td></tr><tr><td><textarea rows="5" cols="30" name="info"></textarea></td></tr><tr><td align="center"><input type="submit" value="提交"></tr></table> </form> </body> </html>創建replace.jsp頁面,獲取表單信息,并調用Bean類的方法實現字符串中空格和回車的轉換
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%request.setCharacterEncoding("UTF-8"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>替換字符串處理頁</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"><style type="text/css">table{border: 1px solid;border-color: green;color: gray;font-size: 12px;}</style></head><body><%String info = request.getParameter("info");%><jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtiil1"></jsp:useBean><jsp:setProperty property="str" name="strBean" value="<%=info %>"/><table width="240" ><tr><td align="center">查看信息結果</td></tr><tr><td height="100" valign="top"><jsp:getProperty property="str" name="strBean"/></td></tr></table> </body> </html>總結
以上是生活随笔為你收集整理的转换输入文本中的回车和空格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 判断用户是否在线
- 下一篇: 计算字符串的实际长度