1. 需要一个字符串替换的函数,因为java自带的函数,遇到特殊的字符就当成正则表达式处理了,我不想这样。
/**
*<br>方法说明:替换字符串函数
*<br>输入参数: strSource - 源字符串; strFrom - 要替换的子串;strTo - 替换为的字符串
*<br>返回类型:替换后的字符串
*/
public static String replace(String strSource, String strFrom, String strTo) {
// 如果要替换的子串为空,则直接返回源串
if (strFrom == null || strFrom.equals(""))
return strSource;
String strDest = "";
// 要替换的子串长度
int intFromLen = strFrom.length();
int intPos;
// 循环替换字符串
int i = 0;
while ((intPos = strSource.indexOf(strFrom)) != -1) {
i++;
System.out.println(i + ": " + strFrom);
// 获取匹配字符串的左边子串
strDest = strDest + strSource.substring(0, intPos);
// 加上替换后的子串
strDest = strDest + strTo;
// 修改源串为匹配子串后的子串
strSource = strSource.substring(intPos + intFromLen);
}
// 加上没有匹配的子串
strDest = strDest + strSource;
// 返回
return strDest;
}
这个是我现在用的函数效率太低了。2.我使用HttpURLConnection访问网页,已经设置了setConnectTimeout和setReadTimeout,但是有一些网页还是长时间无响应,比如下面这些:http://www.bestdata.cn/newscenter/new.asp?thedate=2006-11-23
http://www.frchina.net/forumnew/viewthread.php?tid=87094有谁知道原因吗?
/**
*<br>方法说明:替换字符串函数
*<br>输入参数: strSource - 源字符串; strFrom - 要替换的子串;strTo - 替换为的字符串
*<br>返回类型:替换后的字符串
*/
public static String replace(String strSource, String strFrom, String strTo) {
// 如果要替换的子串为空,则直接返回源串
if (strFrom == null || strFrom.equals(""))
return strSource;
String strDest = "";
// 要替换的子串长度
int intFromLen = strFrom.length();
int intPos;
// 循环替换字符串
int i = 0;
while ((intPos = strSource.indexOf(strFrom)) != -1) {
i++;
System.out.println(i + ": " + strFrom);
// 获取匹配字符串的左边子串
strDest = strDest + strSource.substring(0, intPos);
// 加上替换后的子串
strDest = strDest + strTo;
// 修改源串为匹配子串后的子串
strSource = strSource.substring(intPos + intFromLen);
}
// 加上没有匹配的子串
strDest = strDest + strSource;
// 返回
return strDest;
}
这个是我现在用的函数效率太低了。2.我使用HttpURLConnection访问网页,已经设置了setConnectTimeout和setReadTimeout,但是有一些网页还是长时间无响应,比如下面这些:http://www.bestdata.cn/newscenter/new.asp?thedate=2006-11-23
http://www.frchina.net/forumnew/viewthread.php?tid=87094有谁知道原因吗?
public static String replace(String strSource, String strFrom, String strTo) {
return strSource.replaceAll("\\Q" + strFrom + "\\E", strTo);
}或
public static String replace(String strSource, String strFrom, String strTo) {
return Pattern.compile(strFrom, 0x10).matcher(strSource).replaceAll(strTo));
}2.setConnectTimeout和setReadTimeout应该是设置连接超时与设置读取超时吧
解决URL, 应该还涉及到DNS解析吧, 改用IP试试!
String.replaceAll 这个区分正则你自己测试看看吧!
JAVA资料太多?选中想收藏的文字(图片),右键选“收录到易载”,搞定!
replace的参数只能是字符吧~~~ 楼主是要替换字符串的~~
System.out.println(str.replace(".", "="));
System.out.println(str.replaceAll(".", "="));输出结果为
1234\()[]??**==5678
===================