3

Java Program to Remove all White Spaces from a String

 1 year ago
source link: https://www.geeksforgeeks.org/videos/java-program-to-remove-all-white-spaces-from-a-string/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java Program to Remove all White Spaces from a String

Java Program to Remove all White Spaces from a String
  • 80 Views
  • 12/08/2022

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/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK