Examples
- Hello World Program in Java (Print Hello World in Java)
- Java Program to Add Two Numbers (Java Sum / Addition)
- Find Greatest of Three Numbers in Java (Largest Number Program)
- Prime Number Program in Java (Code to Check Prime or Not)
- Java Program for Fibonacci Series (Using for, while, recursion, scanner)
- Factorial Program in Java (Find Factorial of a Number in Java)
- How to Find Sum of Digits of a Number in Java?
- How to Reverse a Number in Java? Program & Examples
- How to Swap Two Numbers in Java? Programs With/Without Third Variable
- Even Odd Program in Java (Program to Check Number is Even or Odd)
- Vowel and Consonant Program in Java
- Java Program for Quadratic Equation (Find Roots With 3 Ways)
- Find Frequency of Characters in a String in Java (4 Ways)
- Remove Space from String in Java (Remove Whitespace)
- String Null Check in Java (String is Empty or Null) - 5 Ways
- How to Print String in Java? 6 Methods
- How to Get ASCII Value of Char in Java? Find ASCII Value
Remove Space from String in Java (Remove Whitespace)
Manipulating strings is a fundamental task in programming. Strings are used to store and manipulate textual data, and often, you'll come across situations where you need to remove spaces or whitespace from strings in Java. Whether you're working on a simple text processing application or a complex data parsing task, understanding how to remove spaces from strings is a crucial skill.
This tutorial will help you learn how to remove spaces from string in Java. We'll explore various methods and techniques to accomplish this task, catering to different scenarios and use cases.
Use Cases of White Space Removal from Strings
The need to remove whitespace from strings arises in numerous real-world scenarios. Here are some common use cases:
-
Data Validation: When processing user inputs, removing leading, trailing, or extra spaces ensures that the input data is clean and conforms to expected formats.
-
String Comparison: In applications such as search engines or databases, removing spaces from strings before comparison ensures accurate results. For example, "apple" and "app le" should be considered identical when searching.
-
Formatting Output: Stripping unnecessary spaces is essential when generating formatted text, such as reports, invoices, or web pages. Clean output enhances readability and presentation.
-
Tokenization: In lexical analysis or natural language processing, removing spaces is often the first step in breaking a string into meaningful tokens or words.
-
URLs and Paths: When dealing with URLs or file paths, removing spaces is crucial to avoid errors and ensure proper functioning.
Let’s get started and understand multiple approaches to tackle these use cases, from simple methods to more advanced regular expressions.
Concepts to Learn For This Program:
Remove All Spaces from String in Java Using String.replaceAll()
Here's a Java program to remove spaces from a string using the String.replaceAll() method:
Code
public class RemoveSpacesExample {
public static void main(String[] args) {
// Input string with spaces
String inputString = "Hello, World! This is a test string.";
// Removing spaces using String.replaceAll()
String result = inputString.replaceAll(" ", "");
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("String after removing spaces: " + result);
}
}
Output
Original String: Hello, World! This is a test string.
String after removing spaces: Hello,World!Thisisateststring.
Explanation
-
We start with an input string inputString that contains spaces.
-
We use the String.replaceAll() method to replace all occurrences of the space character " " with an empty string "". This effectively removes all spaces from the input string.
-
The modified string is stored in the result variable.
-
Finally, we display both the original and modified strings using System.out.println().
In this example, the String.replaceAll() method provides a straightforward way to remove spaces from a string by replacing them with nothing. This method is suitable for situations where you want to remove all whitespaces from the string in Java.
Remove Space from String in Java Using String.replace()
Here's a Java program to remove spaces from a string using the String.replace() method:
Code
public class RemoveSpacesExample {
public static void main(String[] args) {
// Input string with spaces
String inputString = "Hello, World! This is a test string.";
// Removing spaces using String.replace()
String result = inputString.replace(" ", "");
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("String after removing spaces: " + result);
}
}
Output
Original String: Hello, World! This is a test string.
String after removing spaces: Hello,World!Thisisateststring.
Explanation
-
We start with an input string inputString that contains spaces.
-
We use the String.replace() method to replace all occurrences of the space character " " with an empty string "". This effectively removes all spaces from the input string.
-
The modified string is stored in the result variable.
-
Finally, we display both the original and modified strings using System.out.println().
The String.replace() method is similar to String.replaceAll(), but it replaces all exact occurrences of the specified substring with another string. In this case, we specify the space character " " as the substring to be replaced with an empty string "". This method is also suitable for situations where you want to remove all spaces in the string
Remove Whitespace from String in Java Using StringBuffer or StringBuilder
Here's a Java program to remove whitespaces from a string using the StringBuffer or StringBuilder approach:
Code
public class RemoveSpacesExample {
public static void main(String[] args) {
// Input string with spaces
String inputString = "Hello, World! This is a test string.";
// Create a StringBuilder to build the result
StringBuilder resultBuilder = new StringBuilder();
// Iterate through the characters of the input string
for (char c : inputString.toCharArray()) {
// Check if the character is not a space
if (c != ' ') {
// Append non-space characters to the resultBuilder
resultBuilder.append(c);
}
}
// Convert the StringBuilder back to a string
String result = resultBuilder.toString();
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("String after removing spaces: " + result);
}
}
Output
Original String: Hello, World! This is a test string.
String after removing spaces: Hello,World!Thisisateststring.
Explanation
-
We start with an input string inputString that contains spaces.
-
We create a StringBuilder named resultBuilder. StringBuilder is used to efficiently build and modify strings in Java.
-
We iterate through each character in the input string using a for-each loop and inputString.toCharArray().
-
Inside the loop, we check if the current character c is not a space (i.e., c != ' '). If it's not a space, we append it to the resultBuilder.
-
After processing all characters, we convert the resultBuilder back to a string using the toString() method, and the modified string is stored in the result variable.
Finally, we display both the original and modified strings using System.out.println().
This method allows you to remove spaces from a string by manually iterating through its characters and building a new string without spaces. It provides more flexibility in case you need to perform custom processing while removing spaces.
Remove Whitespace From String Using Regex
Following is a Java program to remove whitespaces from a string using regular expressions with the Pattern and Matcher classes:
Code
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RemoveSpacesExample {
public static void main(String[] args) {
// Input string with spaces
String inputString = "Hello, World! This is a test string.";
// Define a regular expression pattern to match spaces
Pattern pattern = Pattern.compile("\\s");
// Create a Matcher object to match the pattern with the input string
Matcher matcher = pattern.matcher(inputString);
// Use Matcher's replaceAll() method to remove spaces
String result = matcher.replaceAll("");
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("String after removing spaces: " + result);
}
}
Output
Original String: Hello, World! This is a test string.
String after removing spaces: Hello,World!Thisisateststring.
Explanation
-
We start with an input string inputString that contains spaces.
-
We define a regular expression pattern using Pattern.compile("\\s"). This pattern matches all whitespace characters, including spaces, tabs, and line breaks, represented by the escape sequence \\s.
-
We create a Matcher object named matcher and initialize it with the input string by calling pattern.matcher(inputString). This prepares the matcher to search for matches in the input string based on the defined pattern.
-
We use the Matcher's replaceAll("") method to replace all matched spaces with an empty string "". This effectively removes all spaces from the input string.
-
The modified string is stored in the result variable.
-
Finally, we display both the original and modified strings using System.out.println().
This method uses regular expressions to find and replace spaces in the input string. It provides flexibility in handling various types of whitespace characters, making it useful for more complex text manipulation tasks.
Learn Next: