通过在C ++程序中反向交替组合字符串的两半的字符来创建新字符串

在本教程中,我们将编写一个程序,该程序通过以相反的顺序交替组合字符串的两半的字符来创建新的字符串。

让我们看看解决问题的步骤。

  • 初始化字符串。

  • 查找字符串的长度。

  • 存储前一半和后一半字符串索引。

  • 从字符串的两半的结尾开始迭代。

    • 将每个字符添加到新字符串。

  • 打印新字符串。

示例

让我们看一下代码。

#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 = "nhooos";
   getANewString(str);
   return 0;
}
输出结果

如果执行上述程序,则将得到以下结果。

asitrnoitouptsl

结论

猜你喜欢