Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สร้างสตริงใหม่โดยการรวมอักขระสองส่วนของสตริงกลับด้านใน C++ Program


ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่สร้างสตริงใหม่โดยสลับอักขระของสองส่วนของสตริงในลำดับที่กลับกัน

มาดูขั้นตอนการแก้ปัญหากัน

  • เริ่มต้นสตริง

  • หาความยาวของสตริง

  • เก็บดัชนีสตริงครึ่งแรกและครึ่งหลัง

  • วนซ้ำจากจุดสิ้นสุดของสองส่วนของสตริง

    • เพิ่มอักขระแต่ละตัวในสตริงใหม่

  • พิมพ์สตริงใหม่

ตัวอย่าง

มาดูโค้ดกันเลย

#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

บทสรุป

หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น