• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
August 12, 2022 |8.6K Views
Java Program to Remove all White Spaces from a String
  Share   Like
Description
Discussion

In this video, we will write a java program to to remove all white spaces from a String.

Below are the approaches that we have used in this video:

1. Using .charAt() Method
2. Using .toCharArray() Method
3. Using .replaceAll() Method

Method 1: In this method, we are iterating on each index of the String and getting the character present at the index using .charAt() method. If the character is not a space, then we are adding that character into a new result string.

Method 2: In this method, we are using .toCharArray() to convert a String to an array of characters. Then we iterate on the character
array and the characters that are not white spaces, we concat those characters into a new String variable.

Method 3: In this method, we are using replaceAll() method of String and a regex to replace all white spaces from a string. We can either use \\s+ or \\s as a pattern to remove all white space characters, including tab characters.

How to remove all white spaces from a String in Java?
https://www.geeksforgeeks.org/how-to-remove-all-white-spaces-from-a-string-in-java/

Read More