需求:String str = "中aacabbbaac中sabbcccdddddeee";
String[] findStr = {"aa","b","c","d","e","f","g"} ;
String[] repStr = {"A","B","C","D","E","F","G"} ;
在str中查找findStr中的字符串,如果找到则替换成与findSt索引位置对应的repStr数组中的字符串元素。
方法一:int len = findStr.length ;
for(int i=0 ; i<len ;i++){
str = str.replace(findStr[i], repStr[i]);
}
方法二: int len = findStr.length ;
StringBuffer sf = new StringBuffer(str) ;
for(int i=0 ; i<len ;i++){
while(iStart > -1)
{
iStart = sf.indexOf(gjcMcStr[i]) ;
if(iStart > -1)
sf.replace(iStart, iStart+gjcMcStr[i].length(), gjcTdcStr[i]) ;
else
break ;
}
}
str = sf.toString() ;
方法三:
Map<String,String> map=new HashMap<String,String>();
map.put("aa", "A");
map.put("b", "B");
map.put("c", "C");
map.put("d", "D");
map.put("e", "E");
map.put("f", "F");
map.put("g", "G");
Matcher matcher = Pattern.compile("(?:aa|b|c|d|e|f|g)").matcher(str);
StringBuffer sf = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sf, map.get(matcher.group()));
}
matcher.appendTail(sf);
str = sf.toString() ;