Java program to remove the first and last occurrence of a given character from a string

Given the symbol C and the string S, the task is to remove the first and last occurrences of the character C from the string S.

Examples:

Input: S = “GeekforGeeks”, C = ‘e’ 
Output: GeksforGeks 
Explanation: 
GeekforGeeks -> GekforGeks

Input: S = “helloWorld”, C = ‘l’ 
Output: heloWord

Approach: 

The idea is to loop through the given string at both ends and find the first occurrence of the found C character and delete the corresponding occurrence. Finally, print the results.
Below is an implementation of the above approach:

 

// Java Program to implement
// the above approach
class GFG{

// Function to remove first and last
// occurrence of a given character
// from the given String
static String removeOcc(String s, char ch)
{
	// Traverse the given String from
	// the beginning
	for (int i = 0; i < s.length(); i++)
	{

		// If ch is found
		if (s.charAt(i) == ch)
		{
			s = s.substring(0, i) +
				s.substring(i + 1);
			break;
		}
	}

	// Traverse the given String from
	// the end
	for (int i = s.length() - 1; i > -1; i--)
	{

		// If ch is found
		if (s.charAt(i) == ch)
		{
			s = s.substring(0, i) +
				s.substring(i + 1);
			break;
		}
	}
	return s;
}

// Driver Code
public static void main(String[] args)
{
	String s = "hello world";

	char ch = 'l';

	System.out.print(removeOcc(s, ch));
}
}

// This code is contributed by sapnasingh4991

Output: 

helo word

Time Complexity: O(N) 
Auxiliary Space: O(1)

Submit Your Programming Assignment Details