How to remove all white spaces from a String in Java?
Given a string with white spaces, the task is to remove all white spaces from a string using Java built-in methods.
Examples:
Input: str = " Geeks for Geeks "
Output: GeeksforGeeks
Input: str = " A Computer Science Portal"
Output: AComputerSciencePortal
Method 1: Using string class in built functions
To remove all white spaces from String, use the replaceAll() method of the String class with two arguments, which is
replaceAll("\\s", "");
where \\s is a single space in unicode
Example:
Java
class BlankSpace {
public static void main(String[] args)
{
String str = " Geeks for Geeks " ;
str = str.replaceAll( "\\s" , "" );
System.out.println(str);
}
}
|
Method 2: Using Character Class in built functions
In this case, we are going to declare a new string and then simply add every character one by one ignoring the whiteSpace for that we will use Character.isWhitespace(char c).
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
String str = " Geeks for Geeks " ;
String op = "" ;
for ( int i = 0 ; i < str.length(); i++) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
op += ch;
}
}
System.out.println(op);
}
}
|
Method 3: Using String.replace() method:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
String str = " Geeks for Geeks " ;
String op = str.replace( " " , "" );
System.out.println(op);
}
}
|
Method 4 : Using Java 8 Streams:
Java
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args)
{
String str = " Geeks for Geeks " ;
String op = str.chars()
.filter(c -> !Character.isWhitespace(c))
.mapToObj(c -> String.valueOf(( char ) c))
.collect(Collectors.joining());
System.out.println(op);
}
}
|
Last Updated :
02 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...