w3resource

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') {
    continue;
   } else if (i + 1 < n && arr1[i] == 'a' && arr1[i + 1] == 'c') {
    ++i;
   } 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:

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

Visualize Java code execution (Python Tutor):


Remove given characters from a given string.

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String TEXT = "oobotooorogshŜoootorgo";
    private static final char CHAR = 'Ŝ';
       
    private static final String TEXT_CP = "😍 I love 💕 you Ӝ so much 💕 😍";
    private static final String CHAR_CP = "Ӝ";   // Unicode: \u04DC, Code Point: 1244
    private static final String CHAR_CPS = "💕"; // Unicode: \uD83D\uDC95, Code Point: 128149

    public static void main(String[] args) {        

        System.out.println("Input text: \n" + TEXT);
        System.out.println("Character to remove: " + CHAR + "\n");

        System.out.println("StringBuilder based solution:");
        long startTimeV1 = System.nanoTime();

        String resultV1 = Strings.removeCharacterV1(TEXT, CHAR);

        displayExecutionTime(System.nanoTime() - startTimeV1);
        System.out.println("Result: \n" + resultV1);

        System.out.println();
        System.out.println("Regular expression based solution:");
        long startTimeV2 = System.nanoTime();

        String resultV2 = Strings.removeCharacterV2(TEXT, CHAR);

        displayExecutionTime(System.nanoTime() - startTimeV2);
        System.out.println("Result: \n" + resultV2);

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV3 = System.nanoTime();

        String resultV3 = Strings.removeCharacterV3(TEXT, CHAR);

        displayExecutionTime(System.nanoTime() - startTimeV3);
        System.out.println("Result: \n" + resultV3);
        
        System.out.println();
        System.out.println("Java 8, function-style solution (code point)");  
        System.out.println("Input text: \n" + TEXT_CP);
        System.out.println("Character to remove: " + CHAR_CP + "\n");
        long startTimeV4 = System.nanoTime();
       
        String resultV4 = Strings.removeCharacterV4(TEXT_CP, CHAR_CP);
        
        displayExecutionTime(System.nanoTime() - startTimeV4);
        System.out.println("Result: \n" + resultV4);               
        
        System.out.println();
        System.out.println("Java 8, function-style solution (code point)");  
        System.out.println("Input text: \n" + TEXT_CP);
        System.out.println("Character to remove: " + CHAR_CPS + "\n");
        long startTimeV5 = System.nanoTime();
       
        String resultV5 = Strings.removeCharacterV4(TEXT_CP, CHAR_CPS);
        
        displayExecutionTime(System.nanoTime() - startTimeV5);
        System.out.println("Result: \n" + resultV5);               
    }

    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " ("
                + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public final class Strings {

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    public static String removeCharacterV1(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        StringBuilder sb = new StringBuilder();
        char[] chArray = str.toCharArray();
        for (char c : chArray) {
            if (c != ch) {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    public static String removeCharacterV2(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return str.replaceAll(Pattern.quote(String.valueOf(ch)), "");
    }

    public static String removeCharacterV3(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return str.chars()
                .filter(c -> c != ch)
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());
    }

    public static String removeCharacterV4(String str, String ch) {

        if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
            // or throw IllegalArgumentException            
            return "";
        }

        if (ch.codePointCount(0, ch.length()) != 1) {
            return ""; // there is more than 1 Unicode character in the given String
        }

        int codePoint = ch.codePointAt(0);

        return str.codePoints()
                .filter(c -> c != codePoint)
                .mapToObj(c -> String.valueOf(Character.toChars(c)))
                .collect(Collectors.joining());
    }
}

Sample Output:

Input text: 
oobotooorogshŜoootorgo
Character to remove: Ŝ

StringBuilder based solution:
Execution time: 1010761 ns (1 ms)
Result: 
oobotooorogshoootorgo

Regular expression based solution:
Execution time: 2134203 ns (2 ms)
Result: 
oobotooorogshoootorgo

Java 8, functional-style solution:
Execution time: 108088405 ns (108 ms)
Result: 
oobotooorogshoootorgo

Java 8, function-style solution (code point)
Input text: 
😍 I love 💕 you Ӝ so much 💕 😍
Character to remove: Ӝ

Execution time: 1576462 ns (1 ms)
Result: 
😍 I love 💕 you  so much 💕 😍

Java 8, function-style solution (code point)
Input text: 
😍 I love 💕 you Ӝ so much 💕 😍
Character to remove: 💕

Execution time: 129900 ns (0 ms)
Result: 
😍 I love  you Ӝ so much  😍

Flowchart:

Flowchart: Java String Exercises - Remove given characters from a given string
Flowchart: Java String Exercises - Remove given characters from a given string

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?