Categories: Frequently Asked Java Programs In Interview

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:

package StringPrograms;

import java.util.Scanner;

public class TrimSpacesWithTrimMethod {

        public static String trimSpace(String str) {

                // Assume 0th index is non-space character
                int startNonSpaceIndex = 0;

                // Assume last index is non-space character
                int endNonSpaceIndex = str.length()-1;

                // Store length in a variable
                int strLength = str.length();

                // Convert string into char array
                char[] val = str.toCharArray();

                // Increment startNonSpaceIndex by one until you really find a non space char
                while (startNonSpaceIndex < strLength && val[startNonSpaceIndex] == ' ') {
                        startNonSpaceIndex++;
                }

                // Decrement endNonSpaceIndex by one until you really find a non space char
                // Since we know starting index of a non space char, so we should not exceed
                // that which
                // is taking care by (startNonSpaceIndex < endNonSpaceIndex)
                while (startNonSpaceIndex < endNonSpaceIndex && val[endNonSpaceIndex] == ' ') {
                        endNonSpaceIndex--;
                }

                // Now you have actual starting and ending index of non space char in given
                // string.
                return str.substring(startNonSpaceIndex, endNonSpaceIndex+1);
        }

        public static void main(String[] args) {

                // User input to trim spaces
                Scanner sc = new Scanner(System.in);
                System.out.println("Please enter the string to trim spaces:");

                String userInput = sc.nextLine();

                sc.close();

                System.out.println("You entered with spaces: \"" + userInput+"\"");
                
                System.out.println("String after trimming space: \""+trimSpace(userInput) +"\"");
        }
}

 

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"
=================================================

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

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

Recent Posts

TestNG Tutorials 58: DataProvider in TestNG – Running Test for Specific Set of Data Provided by DataProvider Method – Dataprovider With Indices

By default a Test method is executed for all data set returned by DataProvider. The reason behind this is that…

2 hours ago

TestNG Tutorials 57: DataProvider in TestNG – Passing External Data File Name to DataProvider Method Using TestNG xml

In last post, we have learnt how can we make parameterized DataProvider method in TestNG to provide test data to…

5 hours ago

TestNG Tutorials 56: DataProvider in TestNG – Parameterizing DataProvider Method to Provide Data to Multiple Test Methods

"DataProvider" is an important feature provided by TestNG to provide required test data to test methods to run on. We…

6 hours ago

TestNG Tutorials 55: DataProvider in TestNG – Lazy Initialisation of DataProvider Method – Use of Iterator Return Type

Hello, DataProvider is an important functionality provided by TestNG to achieve Data driven testing or providing a set of different…

2 weeks ago

TestNG Tutorials 54: DataProvider in TestNG – Implementing Object Oriented Concept “Encapsulation” with DataProvider Method

Hello Folks, As part of ongoing series on DataProvider, we will learn "How does Encapsulation ( in OOPS concept) help in…

2 weeks ago

API Testing Tutorial Part 14 – Sending First GET Request in Postman

Hello Folks, As part of our API Testing series, we will see "Sending first GET request in Postman". First of all…

3 weeks ago