so I have task to double number of letter “a” every time it occurs in a string. For example sentence “a cat walked on the road” , at the end must be “aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaa” . I had something like this on my mind but it doubles every charachter, not only “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); }
Advertisement
Answer
You need to check what the char a
is (in your case, ‘a’). Additionally, you do not repeat the characters more than twice in your code, hence not getting the answer you expected: result = result + a + a
only adds ‘a’ twice, not giving you: “aa caaaat waaaaaaaalked…”.
Here is the solution:
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); }