Java: 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.
Visual Presentation:
Sample Solution:
Java Code:
// Importing necessary Java utilities.
import java.util.*;
// Define a class named Main.
public class Main {
// Main method to execute the program.
public static void main(String[] args) {
// Define the input string.
String strg = "abrambabasc";
System.out.println("The given string is: " + strg);
System.out.print("After removing the specified characters, the new string is: ");
// Call the method to remove specific characters from the string.
removeSetofCharacters(strg, "ac", "b");
}
// Method to remove specified characters from the given string.
public static void removeSetofCharacters(String str, String ptn1, String ptn2) {
// Get the length of the string and initialize variables.
int n = str.length(), i;
int ptr = 0;
// Convert the string to a character array.
char[] arr1 = str.toCharArray();
// Loop through each character in the string.
for (i = 0; i < n; ++i) {
// Check conditions to remove characters based on the specified patterns.
if (arr1[i] == 'b') {
continue; // Skip 'b'.
} else if (i + 1 < n && arr1[i] == 'a' && arr1[i + 1] == 'c') {
++i; // Skip 'ac'.
} else {
arr1[ptr++] = arr1[i]; // Copy character to the new position.
}
}
// Create a new character array with the modified string.
char[] ret = Arrays.copyOfRange(arr1, 0, ptr);
// Convert the character array to a string and print the result.
System.out.println(new String(ret));
}
}
Sample Output:
The given string is: abrambabasc After removing the new string is: aramaasc
Flowchart:
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:
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?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/string/java-string-exercise-48.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics