Given a String with white spaces, the task is to remove all white spaces from a string.
Input:
" This is an example "
Output: Thisisanexample
We can solve this problem in the following ways:
for
loop.replaceAll()
method.for
loopclass 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);}}
replaceAll()
methodreplaceAll()
to solve this.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 of Param 1
.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);}}