Replace all occurrences of pi with 3.14 in a given string | Java program to replace all pi in a given String with 3.14 ; Function to replace all occurrences of pi in a given with 3.14 ; Iterate through second last element of the String ; If current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; Append the current letter ; Return the output String ; Driver Code
class GFG { public String replacePi ( String input ) { String output = " " ; int size = input . length ( ) ; for ( int i = 0 ; i < size ; ++ i ) { if ( i + 1 < size && input . charAt ( i ) == ' p ' && input . charAt ( i + 1 ) == ' i ' ) { output += "3.14" ; i ++ ; } else { output += input . charAt ( i ) ; } } return output ; } public static void main ( String args [ ] ) { GFG g = new GFG ( ) ; String input = "2 ▁ * ▁ pi ▁ + ▁ 3 ▁ * ▁ pi ▁ = ▁ 5 ▁ * ▁ pi " ; System . out . println ( g . replacePi ( input ) ) ; } }