Frequently Asked Java Program 23: Java Program to Remove Extra WhiteSpace Between Words In Given String

Problem Statement:

Remove extra white spaces between words. Only one white space is allowed between words. If more than one, remove it. If given string has leading or trailing white spaces, remove them as well. Do not use trim method. Write your own logic.

Example:

You entered with spaces: ”       Make       Selenium         Easy       ”
String after removing extra white space: “Make Selenium Easy”

This program was asked in Sapient.

Problem Solution:

  1. We have trim method which only removes leading and trailing whitespace/s of given string. We do not have any readymade methods to remove white spaces between words.
  2. We need to create a char array from given string which we need to iterate.
  3. If char at given index is a non space char, append it to result string.
  4. If char at given index is a white space, check if resultant string is zero in length. If length of resultant string is zero, go to next iteration. We need to go to next iteration as we do not want any leading white spaces in our resultant string. If length of resultant string is not zero, check if next index char is non space. If it is non space, append char to resultant string else to next iteration.

 

Java Program:

 

Output:

Please enter the string to trim extra whitespaces:
       Make      Selenium       Easy    
You entered with spaces: "       Make      Selenium       Easy    "
String after removing extra white space: "Make Selenium Easy"
===================================================================
Please enter the string to trim extra whitespaces:
Make       selenium      easy
You entered with spaces: "Make       selenium      easy"
String after removing extra white space: "Make selenium easy"
====================================================================

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning