Frequently Asked Java Program 22: Java Program to Trim Whitespace From String Without Using Trim Method

Hello Folks,

This interview question was asked in Deloitte. 

Write a java program to Trim a given string without using inbuilt trim() method of String Class in Java.

trim()” method of String class trims leading and trailing whitespace/s of given string. It does not remove whitespace between words. We need to write logic to do so.

Logic step by step:

  1. We need to find first index of non space char in given string from beginning. Say it First.
  2. We need to find first index of non space char in given string from end. Say it Last.
  3. Return a substring indexing from First till Last.

Detailed Explanation:

  1. Assume first char of given string is a non space char and set starting index of non space char as zero. Now check if it is really a non space char. If it it, finalize starting index as zero else increment index by one and repeat the same till you get a non space char.
  2. Assume last char of given string is a non space char and set last index of non space char as (Length of String-1). Now check if it is really a non space char. If it it, finalize end index as (Length of String-1) else decrement index by one and repeat the same till you get a non space char.
  3. Once Starting and Ending index are finalized, get the substring.

 

Java Program:

 

Output:

Please enter the string to trim spaces:
 Make Selenium Easy 
You entered with spaces: " Make Selenium Easy "
String after trimming space: "Make Selenium Easy"
=================================================
Please enter the string to trim spaces:
      Make Selenium Easy      
You entered with spaces: "      Make Selenium Easy      "
String after trimming 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