在尝试使用jsp上的字符串操作时,我在代码中使用了string.repalace()方法但是我一直在跟踪错误:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 9 in the jsp file: /final2.jsp
Cannot invoke replace(String, String) on the array type String[]
6: public void main (String str) {
7: String [] text = StringUtils.substringsBetween(str,"#","#");
8: for (int i=0; i<text.length;i++) {
9: String newtext = text.replace("#"+text[i]+"#","<b>"+text[i]+"</b>");
10: }
11: //blank line
12: }
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java: 102)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:331)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:469)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
我的代码如下:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@page import="org.apache.commons.lang.StringUtils" %>
<%
final class setext {
public void main (String str) {
String [] text = StringUtils.substringsBetween(str,"#","#");
for (int i=0; i<text.length;i++) {
String newtext = text.replace("#"+text[i]+"#","<b>"+text[i]+"</b>");
}
}
}
%>
答案 0 :(得分:3)
text.replace("#"+text[i]+"#","<b>"+text[i]+"</b>");
text是数组,你不能在数组上调用replace()
你需要首先从数组中获取String,它给String并在该String上调用replace。
String temp = text[i];
temp.replace("#"+text[i]+"#","<b>"+text[i]+"</b>");
答案 1 :(得分:1)
text
是一个字符串数组 - 你的意思是:
String newtext = text[i].replace("#"+text[i]+"#","<b>"+text[i]+"</b>");
其中text[i]
是文本数组中的一个字符串。
虽然看着它,但这句话确实很有道理。
答案 2 :(得分:0)
如果只是根据需要替换“#”:
public void main (String str) {
String [] text = StringUtils.substringsBetween(str,"#","#");
for (int i = 0, n = text.length ; i<n; i++) {
text[i] = text[i].replace("#"+text[i]+"#", "<b>"+text[i]+"</b>");
}
EDITED