Q:

Write a C++ program to create a new string where 'if' is added to the front of a given string. If the string already begins with 'if', return the string unchanged

0

Write a C++ program to create a new string where 'if' is added to the front of a given string. If the string already begins with 'if', return the string unchanged

Sample Output:

if else
if else

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>

using namespace std;

string test(string s)
        {
            if (s.length() > 2 && s.substr(0, 2)=="if")
            {
                return s;
            }
            return "if " + s;
        }
        
int main() 
 {
  cout << test("if else") << endl;  
  cout << test("else") << endl;  
  return 0;    
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now