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: neveropen
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 " ; // Call the replaceAll() method str = str.replaceAll( "\\s" , "" ); System.out.println(str); } } |
neveropen
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
// Importing required libraries import java.io.*; import java.util.*; // Class class GFG { // Main driver method 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); // Checking whether is white space or not if (!Character.isWhitespace(ch)) { op += ch; } } System.out.println(op); } } |
neveropen
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!