Replace all occurrences of pi with 3.14 in a given string | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string replacePi ( string input ) { string output ; int size = input . length ( ) ; for ( int i = 0 ; i < size ; ++ i ) { if ( i + 1 < size and input [ i ] == ' p ' and input [ i + 1 ] == ' i ' ) { output += "3.14" ; i ++ ; } else { output += input [ i ] ; } } return output ; } int main ( ) { string input = "2 ▁ * ▁ pi ▁ + ▁ 3 ▁ * ▁ pi ▁ = ▁ 5 ▁ * ▁ pi " ; cout << replacePi ( input ) ; return 0 ; }