How to remove all white spaces from a String in Java
Problem
Given a String with white spaces, the task is to remove all white spaces from a string.
Example
Input:
" This is an example "
Output: Thisisanexample
Solution
We can solve this problem in the following ways:
- Using a
forloop. - Using the
replaceAll()method.
Using a for loop
Approach
- Convert string to a character array.
- Declare a temporary string.
- Traverse the character array.
- Check if the present character is white space or not.
- If it is not white space, then add it to a temporary string.
- Copy temporary string to original string.
- Print the string.
class Solution {public static void main( String args[] ) {//given stringString str = " This is an example ";//convert string to character arraychar[] arr = str.toCharArray();//take temporary stringString tempStr = "";//traverse all the charactersfor(char c:arr){//if present character is not a white space then add to it temporary stringif(c != ' '){tempStr += c;}}//assign tempStr to strstr = tempStr;//print stringSystem.out.println(str);}}
Using the replaceAll() method
Approach
- We will use the in-built method
replaceAll()to solve this. - The method
replaceAll()will take two parameters:Param 1: Provide the string that needs to be replaced.Param 2: Provide the new string that will be placed in the place ofParam 1.
- This method returns the modified string.
- Pass the returned string to the original string.
- Print the string.
class HelloWorld {public static void main( String args[] ) {//given stringString str = " This is an example ";//replacing the white spacesstr = str.replaceAll(" ","");//print modified stringSystem.out.println(str);}}