在jsp中,不象php那样有许多的现成的字符串处理函数,在jsp中你需要自己编写,下面是几个常用的函数,非常有用!
——————————-
中文处理函数:getstr
public string getstr(string string){
try{
string temp_p=string;
byte[] temp_t=temp_p.getbytes("iso8859-1");
string temp=new string(temp_t);
return temp;
}catch(exception e){}
return "null";
}
————————————
字符串替代函数:在line中,用newstring 替代 oldstring
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;
}
一个实际的运用是用将"\r\n"等回车符替代成"<br>"
——————————————-
下面的函数可以将<替换成<,可以用来发表html源代码
public string escapehtml(string input){
if(input==null||input.length()==0)
return input;
stringbuffer buf=new stringbuffer(input.length()+6);
char ch=a;
for(int i=0;i<input.length();i++){
ch=input.charat(i);
if(ch==<){
buf.append("<");
}
else if(ch==>){
buf.append(">");
}
else{
buf.append(ch);
}
}
return buf.tostring();
}
