java替换第N次出现的字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   | 
 
 
 
 
 
 
      public static String replaceNth(String str, String find, int nthOccurrence, String replace) {         int index = str.indexOf(find);         for(int i = 1; i < nthOccurrence; i++) {             index = str.indexOf(find, index + 1);         }
          if(index != -1) {             str = str.substring(0, index) + replace + str.substring(index + find.length());         }         return str;     }
 
  | 
 
例如我要把第二次出现的张三替换为王富贵

若未匹配到指定字符串则不做处理原样返回

查询指定字符串第N次出现的索引
使用 org.apache.commons.lang.StringUtils 下的 ordinalIndexOf方法
1 2 3
   | int i = StringUtils.ordinalIndexOf("张三,李四,王五,张三,李四,王五,张三,李四,王五", "张三", 2);          System.out.println(i);
  | 
 

若未找到则返回 -1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   | /**      * 在指定字符串中查询某个字符串出现的第 n 次位置      *      * @param str     指定字符串      * @param target  要查询的字符串      * @param n       第 n 次出现的位置      * @return        如果找到了,返回第 n 次出现的位置;否则返回 -1。      */     public static int getIndexOf(String str, String target, int n) {         if (str == null || target == null || n <= 0) {             return -1;         }
          int index = str.indexOf(target); // 找到第一次出现的位置
          // 开始找第 n 次出现的位置         for (int i = 2; i <= n && index != -1; i++) {             index = str.indexOf(target, index + 1);         }
          return index;     }
   | 
 
1 2 3 4 5 6 7
   |  String str = "Talk Is Cheap, Show Me The Code";
  String target = String.valueOf('C');
  int index = getIndexOf(str, target, 2); System.out.println(index);
 
  | 
 
