Java Remove white spaces from String without using replace or replaceAll Method. Remove space without using in-built method Interview Question.

 Remove space without  using in-built  method Interview Question
String without replace or replaceAll Method 

Given a String with white spaces, the task is to remove all white spaces from a string without using
in-built methods of String or without Using replaceAll method of String. 
Interviewer always ask not to use in-built methods while testing your coding skills. 
One of the hardest question in you haven't practice this Question how to remove white Space or tab from String. 

 public class RemoveSpacefromString {

  public static String removeWhiteSpaces(String str)

  //if String is Null or Blank return it with null.
  if(str!=null && !str.toCharArray().isEmpty())

   StringBuilder sb=new StringBuilder();
   char[] arr = str.toCharArray();

   for (int i = 0; i < arr.length; i++)
   int temp = arr[i];

    // 32 ASCII for space and 9 is for Tab or use ' ' and '\t'
   //if(temp != 32 && temp != 9)

   if ( temp != ' '  &&  temp != '\t' )
  return sb.toString();
  return null;

  public static void main(String[] args) {
   Scanner scan=new Scanner(;

   System.out.println("Enter a String");
   String checkforspace=scan.nextLine();

  //You can aslo do null Validation 
   String finalString=removeWhiteSpaces(checkforspace);

Remove White Space Test Case1="A p p le";
Output1 = "Apple";

Remove White Space Test Case2="A    pple";
Output2 = "Apple";

Remove White Space Test Case3="      ";
Output3 = null;

Remove White Space Test Case3=null;
Output3 = null;

Post a Comment

Previous Post Next Post