Java program to remove the first and last character of each word in a string

Given the string the task is to remove the first and last character of each word in a string.

Examples: 

Input: Geeks for geeks
Output: eek o eek

Input: Geeksforgeeks is best
Output: eeksforgeek  es

Approach 

  • Split the String based on the space
  • Run a loop from the first letter to the last letter.
  • Check if the character is the starting or end of the word
  • Remove this character from the String.

Below is the implementation of the above approach. 

 

// Java program to remove the first
// and last character of each word in a string.

import java.util.*;

class GFG {
	static String FirstAndLast(String str)
	{

		// Split the String based on the space
		String[] arrOfStr = str.split(" ");

		// String to store the resultant String
		String res = "";

		// Traverse the words and
		// remove the first and last letter
		for (String a : arrOfStr) {
			res += a.substring(1, a.length() - 1) + " ";
		}

		return res;
	}

	// Driver code
	public static void main(String args[])
	{
		String str = "Geeks for Geeks";
		System.out.println(str);
		System.out.println(FirstAndLast(str));
	}
}

Output: 

Geeks for Geeks
eek o eek

 

Submit Your Programming Assignment Details