C++ Exercises: Create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string
Characters at Index 0, 1, 4, 5, ...
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:

Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to extract characters from an input string at indices 0, 1, 4, 5, 8, 9, etc., and form a new string.
- Write a C++ program that reads a string and outputs a new string composed of characters at positions following the pattern: 0,1, then every 4th and 5th character.
- Write a C++ program to generate a patterned substring by picking characters from specific indexes (0, 1, 4, 5, 8, 9, ...) of the original string.
- Write a C++ program that processes a string and forms a new string using characters at predetermined indices that follow the given repeating pattern.
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?