当前位置: 技术问答>java相关
如何将string中\号替换成/号,replace好象不行!!!
来源: 互联网 发布时间:2015-05-27
本文导语: 如何将string中号替换成/号,replace好象不行!!! | /** * 使用replaceString替换targetString中的matchString * @param targetString 源字符串 * @param matchString 匹配子串 * @par...
如何将string中号替换成/号,replace好象不行!!!
|
/**
* 使用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 = "";
}
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 = "";
}
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;
}