在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 = "tutorialspoints";
getANewString(str);
return 0;
}输出
如果您执行以上程序,则将获得以下结果。
asitrnoitouptsl
结论
如果您对本教程有任何疑问,请在评论区留言。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP