มีหลายวิธีที่กำหนดไว้ในการย้อนกลับสตริงในโค้ด C++ ซึ่งรวมถึงสแต็ก แทนที่ และการวนซ้ำ ในตัวอย่างนี้ สตริงอย่างง่ายจะถูกย้อนกลับแบบวนซ้ำโดยใช้อัลกอริธึมต่อไปนี้
อัลกอริทึม
START Step-1: Input the string Step-2: Get the length of the string using length() method Step-3: Swap the last character to first using for loop Step-4: Print END
ความเข้ากันไม่ได้ของการคำนวณข้างต้น โค้ดที่แนบมาในภาษา c++ ได้ลองทำดังต่อไปนี้
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
void strReverse(string& str){
int n = str.length();
// Swap character starting from two
cout<<"interative reverse (Tomhanks)::";
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int main(){
string str = "Tomhanks";
strReverse(str);
cout << str;
return 0;
} ผลลัพธ์
ตามที่รวบรวมไว้ข้างต้น สตริงที่กำหนด “Tomhanks” จะถูกพิมพ์ในลำดับที่กลับกันดังนี้
Iterative reverse (Tomhanks):: sknahmoT