Here you can find the source of replaceSign(String sourceStr, char startc, char endc, String replaceStr)
Parameter | Description |
---|---|
sourceStr | sourceStr |
startc | start char |
endc | end char |
replaceStr | replaceStr |
public static String replaceSign(String sourceStr, char startc, char endc, String replaceStr)
//package com.java2s; import java.util.ArrayList; import java.util.List; public class Main { /**//from w w w .j a va 2s . c o m * * @param sourceStr * sourceStr * @param startc * start char * @param endc * end char * @param replaceStr * replaceStr * @return new String * @author j00105185 */ public static String replaceSign(String sourceStr, char startc, char endc, String replaceStr) { char[] cs = sourceStr.toCharArray(); int i = 0; int index = 0; int startindex = -1; int endindex = -1; List<int[]> list = new ArrayList<int[]>(); for (char c : cs) { if (c == startc) { if (index == 0) { startindex = i; } index++; } if (c == endc) { if (index == 1) { endindex = i; int[] indexs = { startindex, endindex }; list.add(indexs); startindex = -1; endindex = -1; } index--; } i++; } return replace(sourceStr, list, replaceStr); } /** * * @param sourceStr * sourceStr * @param indexList * indexList * @param replaceStr * replaceString * @return new String * @author j00105185 */ public static String replace(String sourceStr, List<int[]> indexList, String replaceStr) { if (indexList.isEmpty()) { return sourceStr; } StringBuffer bf = new StringBuffer(); int t = 0; int i = 0; for (int[] ii : indexList) { bf.append(sourceStr.substring(t, ii[0]).trim()).append(replaceStr); if (i == indexList.size() - 1) { bf.append(sourceStr.substring(ii[1] + 1).trim()); } i++; t = ii[1] + 1; } return bf.toString().trim(); } }