2012-07-18 181 views
0

尝试使用jsp上的字符串操作时,我在代码中使用了string.repalace()方法,但我持续出现以下错误:无法在数组类型String上调用replace(String,String)[]

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>"); 
    } 

} 

} 
%> 

回答

3
text.replace("#"+text[i]+"#","<b>"+text[i]+"</b>"); 

文字是数组,你不能调用数组replace()

您需要首先从数组中获取字符串,并在该字符串上给出字符串并调用replace。

String temp = text[i]; 
temp.replace("#"+text[i]+"#","<b>"+text[i]+"</b>"); 
1

text是字符串数组 - 你可能意味着:

String newtext = text[i].replace("#"+text[i]+"#","<b>"+text[i]+"</b>"); 

其中text[i]是文本数组中的字符串之一。

虽然看它,但这种说法确实很有意义。

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

  • 加入ñ为(..)
  • 如果您的代码段强调你也可以使用模式/匹配器模型来代替'#'。
相关问题