Java String Exercises: Remove "b" and "ac" from a given string

Java String: Exercise-48 with Solution

Write a Java program to remove "b" and "ac" from a given string.

Pictorial Presentation:

Java String Exercises: Remove

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static void main(String[] args) {
  String strg = "abrambabasc";
  System.out.println("The given string is: " + strg);
  System.out.print("After removing the new string is: ");
  removeSetofCharacters(strg, "ac", "b");
 public static void removeSetofCharacters(String str, String ptn1, String ptn2) {
  int n = str.length(), i;
  int ptr = 0;
  char[] arr1 = str.toCharArray();
  for (i = 0; i < n; ++i) {
   if (arr1[i] == 'b') {
   } else if (i + 1 < n && arr1[i] == 'a' && arr1[i + 1] == 'c') {
   } else {
    arr1[ptr++] = arr1[i]; // Copy char to head.
  char[] ret = Arrays.copyOfRange(arr1, 0, ptr);
  System.out.println(new String(ret));

Sample Output:

The given string is: abrambabasc
After removing the new string is: aramaasc


Flowchart: Java String Exercises - Remove 'b' and 'ac' from a given string

Visualize Java code execution (Python Tutor):

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to rearrange a string so that all same characters become d distance away.
Next: Write a Java program to find first non-repeating character from a stream of characters.

What is the difficulty level of this exercise?

Inviting useful, relevant, well-written and unique guest posts