/**
* 使用replaceString替换targetString中的matchString
* @param targetString 源字符串
* @param matchString 匹配子串
* @param replaceString 替换字符串
* @return 处理后的源字符串
*/
public final static String replaceString( String targetString,
String matchString,
String replaceString )
{
String out;
int targetLength = targetString.length();
int replaceLength = replaceString.length();
int matchLength = matchString.length();
StringTokenizer st = new StringTokenizer( targetString, matchString );
int firstIndex = targetString.indexOf( matchString ); if ( firstIndex < 0 )
{
// 无匹配
out = targetString; return out;
} if ( firstIndex > 0 )
{
out = "";
}
else
{
// 以要替换的字符串开头
out = replaceString;
} while ( st.hasMoreTokens() )
{
out += st.nextToken() + replaceString;
} out = out.substring( 0, out.length() - replaceLength ); int lastIndex = targetString.lastIndexOf( matchString ); // 以要替换的字符串结尾
if ( lastIndex == ( targetLength - matchLength ) )
{
out = out + replaceString;
} return out;
}
* 使用replaceString替换targetString中的matchString
* @param targetString 源字符串
* @param matchString 匹配子串
* @param replaceString 替换字符串
* @return 处理后的源字符串
*/
public final static String replaceString( String targetString,
String matchString,
String replaceString )
{
String out;
int targetLength = targetString.length();
int replaceLength = replaceString.length();
int matchLength = matchString.length();
StringTokenizer st = new StringTokenizer( targetString, matchString );
int firstIndex = targetString.indexOf( matchString ); if ( firstIndex < 0 )
{
// 无匹配
out = targetString; return out;
} if ( firstIndex > 0 )
{
out = "";
}
else
{
// 以要替换的字符串开头
out = replaceString;
} while ( st.hasMoreTokens() )
{
out += st.nextToken() + replaceString;
} out = out.substring( 0, out.length() - replaceLength ); int lastIndex = targetString.lastIndexOf( matchString ); // 以要替换的字符串结尾
if ( lastIndex == ( targetLength - matchLength ) )
{
out = out + replaceString;
} return out;
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货