当前位置: 技术问答>java相关
求字符替换现成函数 (\n换成<br>之类)
来源: 互联网 发布时间:2017-05-02
本文导语: 我在网上找的code贴在jsp文件都全部都出错,真是郁闷死了 public String replace( String line, String oldString, String newString ) { int i=0; if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) { char [] line2 = line.toCharArray(); char ...
我在网上找的code贴在jsp文件都全部都出错,真是郁闷死了
public String replace( String line, String oldString, String newString )
{
int i=0;
if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
char [] line2 = line.toCharArray();
char [] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while( ( i=line.indexOf( oldString, i ) ) > 0 ) {
buf.append(line2, j, i-j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
给我贴一个好用的函数吧...谢谢各位了...
public String replace( String line, String oldString, String newString )
{
int i=0;
if ( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
char [] line2 = line.toCharArray();
char [] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while( ( i=line.indexOf( oldString, i ) ) > 0 ) {
buf.append(line2, j, i-j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
给我贴一个好用的函数吧...谢谢各位了...
|
jdk1.4中有个很好用的函数,replaceAll(),你可以用它来替换所得到的所有字符,比如replaceAll("n","
")
")
|
public String replace(String line,String ch,String rep)
{
int i=line.indexOf(ch);
StringBuffer sb=new StringBuffer();
if (i==-1)
return line;
sb.append(line.substring(0,i)+rep);
if(i+ch.length()')
stringbuffer.append(">");
else
if(c == '"')
stringbuffer.append(""");
else
if(c == '&')
stringbuffer.append("&");
else
stringbuffer.append(c);
}
return stringbuffer.toString();
}
{
int i=line.indexOf(ch);
StringBuffer sb=new StringBuffer();
if (i==-1)
return line;
sb.append(line.substring(0,i)+rep);
if(i+ch.length()')
stringbuffer.append(">");
else
if(c == '"')
stringbuffer.append(""");
else
if(c == '&')
stringbuffer.append("&");
else
stringbuffer.append(c);
}
return stringbuffer.toString();
}