每次新出现时加倍一个字母

Doubling one letter with each new occurence

所以我的任务是每次出现在字符串中时将字母“a”的数量加倍。 例如句子“a cat walked on the road”,最后一定是“aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaa”。我脑子里有这样的想法,但它使每个字符都加倍,而不仅仅是“a”。

    public static void main(String[] args) {
    String s = "a bear walked on the road";
    String result = "";
    int i = 0;
    while(i<s.length()){
        char a = s.charAt(i);
        result = result + a + a;
        i++;
    }
    System.out.println(result);
}

试试这个:

public static void main(String[] args) {
    char letterToSearch = 'a'
    String myString = "a bear walked on the road";
    StringBuilder result = new StringBuilder();
    int occurrance = 0;
    for (int i = 0; i < myString.length(); i++){
        char currChar = myString.charAt(i);
        if (currChar == letterToSearch){
            occurrance+=1;
            for (int j = 0; j < 2*occurrance; j++){
                result.append(currChar);
            }
        } else {
            result.append(currChar);
        }
    }
    System.out.println(result);
}

变量 occurrance 跟踪您有多少 a

您需要检查 char a 是什么(在您的情况下,'a')。此外,您在代码中重复字符的次数不会超过两次,因此不会得到您期望的答案:result = result + a + a 仅添加 'a' 两次,not 给您: "aa caaaat waaaaaaaalked...".

解决方法如下:

public static void main(String[] args) {
    String s = "a bear walked on the road";
    String result = "";
    char lookingFor = 'a'; // Can change this to whatever is needed
    int counter = 2;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == lookingFor) { // The current character is what we need to be repeated.
            
            // Repeat the character as many times as counter is (each loop: 2, 4, 6, 8, ...)
            for (int j = 0; j < counter; j++) {
                result += lookingFor;
            }

            counter *= 2; // Double counter at every instance of 'a'
        }
        else { // The current char is not what we are looking for, so we just add it to our result.
            result += s.charAt(i);
        }
    }
    System.out.println(result);
}

问题是:

  • 你将每个字符加倍,因为你没有测试它是否是 'a'。
  • 而且你每次都没有加倍替换。

这是您的解决方案的修改版本。

String s = "a bear walked on the road";
String result = "";
String sub = "aa";
int i = 0;
while(i<s.length()){
    // get the character
    char ch = s.charAt(i++);
    //if it an a, append sub to result
    // and double sub.
    if (ch == 'a') {
          result +=  sub;
          sub += sub;
    } else {
        // otherwise, just append the character
        result += ch;
    }
}

这是另一种方法。

  • 检查每个字符并在每次遇到 a 时加倍替换。
String str = "a cat walked on the road";
StringBuilder sb = new StringBuilder();
String sub = "a";
for (String s : str.split("")) {
    sb.append(s.equals("a") ? (sub += sub) : s);
}
        
System.out.println(sb);

打印

aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaad