删除字符串中某个指定字符 (删除第几个“a”)

时间:2021-09-13 10:48:20

删除某个字符串中的指定字符

例如:"asdasdasdasdasdsaaadasdadas",删除第三个"d"

java代码:

package com.qf.test;

public class TestStr {
	
	public static void main(String[] args) {
		String str = "asdasdasdasdasdsaaadasdadas";
		System.out.println(remove(str, "d", 3));
	}
	
	private static String remove(String str , String targetStr , int index) {
		
		int i = str.indexOf(targetStr);
		
		String resultStr = "";
		
		if(index == 1) {
			return str.replaceFirst(targetStr, "");
		}else {
			resultStr = str.substring(0, i+1);
			str = str.substring(i+1);
			resultStr = resultStr + remove(str, targetStr, index-1);
		}
		
		return resultStr;
	}
}

console打印:

asdasdasasdasdsaaadasdadas