w3resource

C++ Exercises: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back

C++ Basic Algorithm: Exercise-11 with Solution

Write a C++ program to create a string taking the first 3 characters of a given string. Then, return the string with the 3 characters added to both the front and back. If the given string length is less than 3, use whatever characters are there.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

string  test(string str)
        {
             if (str.length() < 3)
            {
                return str + str + str;
            }
            else
            {
                string front = str.substr(0, 3);
                return front + str + front;
            }
        }
        
int main() 
 {
  cout << test("Python") << endl;  
  cout << test("JS") << endl;  
  cout << test("Code") << endl;  
  return 0;    
}

Sample Output:

PytPythonPyt
JSJSJS
CodCodeCod

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back.

Flowchart:

Flowchart: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to check if a given positive number is a multiple of 3 or a multiple of 7.
Next: Write a C++ program to check if a given string starts with 'C#' or not.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

Program being compiled differently in 3 major C++ compilers. Which one is right?

GCC is correct, at least according to C++11 lookup rules. 3.4.3.1 [class.qual]/2 specifies that, if the nested name specifier is the same as the class name, it refers to the constructor not the injected class name. It gives examples:

B::A ba;           // object of type A
A::A a;            // error, A::A is not a type name
struct A::A a2;    // object of type A

It looks like MSVC misinterprets it as function-style cast expression creating a temporary C with y as a constructor parameter; and Clang misinterprets it as a declaration of a variable called y of type C.

Ref: https://bit.ly/3ww1Bna

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook