text: Remove the first and last occurrence of a given Character from a String | C ++ Program to implement the above approach ; Function to remove first and last occurrence of a given character from the given string ; Traverse the given string from the beginning ; If ch is found ; Traverse the given string from the end ; If ch is found ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeOcc ( string & s , char ch ) { for ( int i = 0 ; s [ i ] ; i ++ ) { if ( s [ i ] == ch ) { s . erase ( s . begin ( ) + i ) ; break ; } } for ( int i = s . length ( ) - 1 ; i > -1 ; i -- ) { if ( s [ i ] == ch ) { s . erase ( s . begin ( ) + i ) ; break ; } } return s ; } int main ( ) { string s = " hello ▁ world " ; char ch = ' l ' ; cout << removeOcc ( s , ch ) ; return 0 ; }