ในโปรแกรมนี้ เราจะมาดูวิธีการวนซ้ำอักขระแต่ละตัวของสตริงในภาษา C++ ในการวนซ้ำอักขระแต่ละตัว เราสามารถใช้การวนซ้ำตั้งแต่ 0 ถึง (ความยาวสตริง – 1) สำหรับการเข้าถึงอักขระ เราสามารถใช้ตัวดำเนินการตัวห้อย "[ ]" หรือฟังก์ชัน at() ของวัตถุสตริงได้
Input: A string “Hello World” Output: “Hello World”
อัลกอริทึม
Step 1: Get the string Step 2: Use R before string to make it raw string Step 3: End
โค้ดตัวอย่าง
#include<iostream>
using namespace std;
main() {
string my_str = "Hello World";
for(int i = 0; i<my_str.length(); i++) {
cout << my_str.at(i) << endl; //get character at position i
}
} ผลลัพธ์
H e l l o W o r l d