Learning Center
Java

How to Remove a Character from a String in Java

29 Mar 2024
JC Brian Refugia
JC Brian Refugia

Java strings, which are commonly used in Java programming, are sequence of characters. In the Java programming language, strings are considered objects of the String class. The Java platform includes the String class for creating and manipulating strings. Strings in Java are immutable, which means that once formed, they cannot be modified. Using a variety of string manipulation techniques, a new string can be built based on existing ones. Below are some of the common methods on how to remove characters from string in Java: 

  • Using the replace method

  • Using the StringBuilder class

  • Using Regular Expressions

Replace Method
Copy link

This string.replace(replstr, newstr) method is used to replace a portion of a supplied string with another string or a regex. The original string will remain unchanged. 

Example: 

Image2

Output: Replacing 'World' with 'Florida'.

Image3

StringBuilder class
Copy link

The StringBuilder class is not built-in in JavaScript. However, you can obtain equivalent functionality through a variety of approaches. One typical method is to use an array to create the updated string and then join it together at the end.

Example:

Image6

Output: 

  • Loop through every character in the original string;

  • Push the character to the modifiedString” array if it is not the character to remove;

  • Combine the elements of the modifiedString array into a single string.

Image5

Regular Expressions
Copy link

In Java, regular expressions (regex) are an extremely useful tool for manipulating strings. They offer a flexible and concise method for searching, replacing, and manipulating text based on patterns. The global (g) flag can be used to replace all occurrences of a string in JavaScript with a regular expression.

Ex:

Image4

Output:

Image1

Conclusion
Copy link

Ultimately, understanding the various ways for removing characters from strings in Java allows developers to approach string manipulation tasks with confidence and efficiency. Whether using built-in string methods, StringBuilder, regular expressions, or iterative approaches, understanding these methodologies enables developers to create robust and maintainable Java applications that meet the diverse needs of modern software development. 

By the way, with Hostman, you can run your workloads on an efficient Amsterdam VPS that support low latency for EU-based users. Check this out, we have plenty of budget VPS hosting options for your projects. Begin your cloud journey with Hostman's Cloud Servers for only $4.