ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมสร้างสตริงใหม่โดยการรวมตัวอักษรสลับกันจากสองครึ่งของสตริงเดิมในลำดับย้อนกลับ (reverse)
ขั้นตอนการแก้ปัญหา
- กำหนดสตริงต้นฉบับ
- หาความยาวของสตริง
- กำหนดดัชนีของครึ่งแรกและครึ่งหลัง
- วนลูปจากท้ายสุดของทั้งสองครึ่ง:
- เพิ่มตัวอักษรแต่ละตัวเข้าไปในสตริงใหม่
- พิมพ์สตริงใหม่
โค้ดตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
void getANewString(string str) {
int str_length = str.length();
int first_half_index = str_length / 2;
int 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
คำอธิบาย
สตริง "tutorialspoints" มีความยาว 15 ตัวอักษร ครึ่งแรกคือ "tutor" (5 ตัว) ครึ่งหลังคือ "ialspoints" (10 ตัว) โปรแกรมจะนำตัวอักษรจากท้ายของแต่ละครึ่งมารวมกันสลับกัน: s(ครึ่งหลัง) + r(ครึ่งแรก) + t(ครึ่งหลัง) + u(ครึ่งแรก) + ... ได้ผลลัพธ์ "asitrnoitouptsl"