+92 332 4229 857 99ProjectIdeas@Gmail.com

How to remove spaces from a string (Java)


How to remove spaces from a string (Java):

 The following code shows you how to remove spaces from a string.

Code


String str1 = "i proud to be a pakistani";

String str = null;
             
The function .replaceAll() is a built in function of String class which takes two arguments first that is to replace and the second one to replace with what? so here our goal is to remove spaces from string so in first argument we would give space (" ") and in the second argument we give empty blank (""):

       str = str1.replaceAll(" ", "");
             
System.out.println("Spaces are removed from str1, now str1 is : " + str);

Output of the program is:

Spaces are removed from str1 , now str1 is : iproudtobeapakistani

ANOTHER WAY:

StringBuffer stringBuff = new StringBuffer();
             
       for (int i = 0 ; i < str1.length() ; i++) {
                    
Here, checking in a string if it is a letter then append that letter to StringBuffer, so all characters excluding of spaces are in our StringBuffer object, so we display it at the end:

              if (Character.isLetter(str1.charAt(i))) {
                                                             
                     stringBuff.append(str1.charAt(i));
              }
       }
             
System.out.println("Spaces are removed from str1 : " + stringBuff);

Output of the program is:

Spaces are removed from str1 : iproudtobeapakistani

0 comments: