Computer >> Computer tutorials >  >> Programming >> C++

Create a new string by alternately combining the characters of two halves of the string in reverse in C++ Program


In this tutorial, we are going to write a program that creates a new string by alternately combining the characters of the two halves of the string in reverse order.

Let's see the steps to solve the problem.

  • Initialize the string.

  • Find the length of the string.

  • Store the first half and second half string indexes.

  • Iterate from the ending of the two halves of the string.

    • Add each character to the new string.

  • Print the new string.

Example

Let's see the code.

#include <bits/stdc++.h>
using namespace std;
void getANewString(string str) {
   int str_length = str.length();
   int first_half_index = str_length / 2, second_half_index = str_length;
   string new_string = "";
   while (first_half_index > 0 && second_half_index > str_length / 2) {
      new_string += str[first_half_index - 1];
      first_half_index--;
      new_string += str[second_half_index - 1];
      second_half_index--;
   }
   if (second_half_index > str_length / 2) {
      new_string += str[second_half_index - 1];
      second_half_index--;
   }
   cout << new_string << endl;
}
int main() {
   string str = "tutorialspoints";
   getANewString(str);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

asitrnoitouptsl

Conclusion

If you have any queries in the tutorial, mention them in the comment section.