Replace all occurrences of string AB with C without using extra space | Efficient Java program to replace all occurrences of " AB " with " C " ; Index in modified string ; Index in original string ; Traverse string ; Replace occurrence of " AB " with " C " ; Increment j by 2 ; add a null character to terminate string ; Driver code
import java . io . * ; class GFG { static void translate ( char str [ ] ) { int len = str . length ; if ( len < 2 ) return ; int i = 0 ; int j = 0 ; while ( j < len - 1 ) { if ( str [ j ] == ' A ' && str [ j + 1 ] == ' B ' ) { j = j + 2 ; str [ i ++ ] = ' C ' ; continue ; } str [ i ++ ] = str [ j ++ ] ; } if ( j == len - 1 ) str [ i ++ ] = str [ j ] ; str [ i ] = ' ▁ ' ; str [ len - 1 ] = ' ▁ ' ; } public static void main ( String args [ ] ) { String st = " helloABworldABGfG " ; char str [ ] = st . toCharArray ( ) ; translate ( str ) ; System . out . println ( " The ▁ modified ▁ string ▁ is ▁ : " ) ; System . out . println ( str ) ; } }