- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Remove All Whitespaces from a String
In this article, we will understand how to remove all whitespaces from a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).
Below is a demonstration of the same −
Suppose our input is −
Input string: Java programming is fun to learn.
The desired output would be −
The string after replacing white spaces: Javaprogrammingisfuntolearn.
Algorithm
Step 1 - START Step 2 - Declare two strings namely String input_string and result. Step 3 - Define the values. Step 4 - Use the function replaceAll("\s", "") to replaces all the white spaces with blank spaces. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class Demo { public static void main(String[] args) { String input_string = "Java programming is fun to learn."; System.out.println("The string is defined as: " + input_string); String result = input_string.replaceAll("\s", ""); System.out.println("\nThe string after replacing white spaces: " + result); } }
Output
The string is defined as: Java programming is fun to learn. The string after replacing white spaces: Javaprogrammingisfuntolearn.
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class Demo { public static String string_replace(String input_string){ String result = input_string.replaceAll("\s", ""); return result; } public static void main(String[] args) { String input_string = "Java programming is fun to learn."; System.out.println("The string is defined as: " + input_string); String result = string_replace(input_string); System.out.println("\nThe string after replacing white spaces: " + result); } }
Output
The string is defined as: Java programming is fun to learn. The string after replacing white spaces: Javaprogrammingisfuntolearn.
Advertisements