【java】在字符串中用递归插入符号

QAQ 求问,怎么使用递归的方法将一组字符串里两个相邻且重复的字符间插入“*”

例:aabxdf
output:a*abxdf

public static String sepStar (String input){
}

ChatGPT尝试解答您的问题
递归方法通常会有两部分组成:

  • 递归终止条件:当字符串的长度小于等于 1 时,返回字符串本身。
  • 递归过程:若字符串的长度大于 1,则判断当前字符和下一个字符是否相同。若相同,则在两个相同的字符中间插入 "*",然后对字符串的剩余部分调用递归方法;若不相同,则将当前字符拼接到字符串的剩余部分的结果之前。

下面是完整的代码:

public static String sepStar(String input) {
    // 递归终止条件
    if (input.length() <= 1) {
        return input;
    }

    // 递归过程
    String result = "";
    if (input.charAt(0) == input.charAt(1)) {
        // 在两个相同的字符中间插入 "*"
        result += input.charAt(0) + "*";
        // 对字符串的剩余部分调用递归方法
        result += sepStar(input.substring(1));
    } else {
        // 将当前字符拼接到字符串的剩余部分的结果之前
        result += input.charAt(0);
        result += sepStar(input.substring(1));
    }

    return result;
}

使用方法:

String input = "aabxdf";
String result = sepStar(input);
System.out.println(result);  // 输出:a*abxdf

仅供参考,希望对您有所启发

public String sepStar (String input){
        String output = "";
        char now, next;
        for (int i = 0; i < input.length()-1; i++) {
            now = input.charAt(i);
            next = input.charAt(i+1);
            if (now == next) {
                output += (now+"*");
            } else {
                output += now;
            }
        }
        return output;
    }