Table of Contents
In this post, we will see how to remove all white spaces from String in java.
When you run above program, you will get below output:
There are multiple ways to remove spaces from String.
- Using ReplaceAll
- Using Iteration
Using ReplaceAll :
You can simply call ReplaceAll method to remove white spaces as shown below.
1 2 3 |
String result1 = str.replaceAll("\s", ""); |
Using iteration :
You can iterate over String using charAt and check if Character is whitespace or not.
Java Program to remove all white spaces from String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; public class StringRemoveSpacesAllMain { public static void main(String[] args) { String str = " Hello world from java2blog.com "; System.out.println("------------------------------"); System.out.println("Using replaceAll"); System.out.println("------------------------------"); // Using replaceAll String result1 = str.replaceAll("\s", ""); System.out.println(result1); String result2 = ""; // Using iteration System.out.println("n------------------------------"); System.out.println("Using Iteration"); System.out.println("------------------------------"); for (int i = 0; i < str.length(); i++) { if (!Character.isWhitespace(str.charAt(i))) { result2 += str.charAt(i); } } System.out.println(result2); } } |
1 2 3 4 5 6 7 8 9 10 11 |
------------------------------ Using replaceAll ------------------------------ Helloworldfromjava2blog.com ------------------------------ Using Iteration ------------------------------ Helloworldfromjava2blog.com |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.