Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string

C++ Basic Algorithm: Exercise-34 with Solution

Write a C++ program to create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string.

Sample Solution:

C++ Code :

#include <iostream>
 
using namespace std;

string test(string str1)
          {
           string result = "";
            for (int i = 0; i < str1.length(); i += 4)
            {
                int c = i + 2;
                int n = 0;
                n += c > str1.length() ? 1 : 2;
                result += str1.substr(i, n);
            }
            return result;
        }
        
int main() 
 {
  cout << test("Python") << endl; 
  cout << test("JavaScript") << endl; 
  cout << test("HTML") << endl;     
  return 0;    
}

Sample Output:

Pyon
JaScpt
HT 

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string.

Flowchart:

Flowchart: Create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string from a given string where a specified character have been removed except starting and ending position of the given string.
Next: Write a C++ program to count the number of two 5's are next to each other in an array of integers. Also count the situation where the second 5 is actually a 6.

What is the difficulty level of this exercise?