在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