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 the 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;

// Function to process a string in chunks and concatenate substrings
string test(string str1)
{
    string result = "";

    // Loop through the string in increments of 4 characters
    for (int i = 0; i < str1.length(); i += 4)
    {
        int c = i + 2; // Calculate the index 'c'

        int n = 0;
        n += c > str1.length() ? 1 : 2; // Determine the length of the substring

        // Append the substring of length 'n' to the 'result' string
        result += str1.substr(i, n);
    }
    return result; // Return the processed string
}

int main() 
{
    // Test cases to process strings in chunks and concatenate substrings
    cout << test("Python") << endl;
    cout << test("JavaScript") << endl; 
    cout << test("HTML") << endl; 

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

Pyon
JaScpt
HT 

Visual 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?



Follow us on Facebook and Twitter for latest update.