โปรแกรมนี้มีจุดประสงค์เพื่อแทนที่คำเฉพาะในสตริงด้วยเครื่องหมายดอกจัน (*) โดยใช้โค้ด C++ ฟังก์ชันสำคัญของคลาส vector และ string มีบทบาทสำคัญในการบรรลุผลลัพธ์ที่ต้องการ อัลกอริทึมมีดังนี้
อัลกอริทึม
เริ่มต้น ขั้นตอนที่ 1: รับสตริงเข้ามา ขั้นตอนที่ 2: แยกสตริงเป็นคำและเก็บในอาร์เรย์ลิสต์ ขั้นตอนที่ 3: วนลูปจนครบความยาวและใส่เครื่องหมายดอกจันลงในตัวแปร ขั้นตอนที่ 4: วนลูปผ่านอาร์เรย์ด้วย foreach และเปรียบเทียบสตริงกับคำที่ต้องการแทนที่ ขั้นตอนที่ 5: แสดงผล จบ
โค้ดต่อไปนี้ถูกเขียนขึ้นตามอัลกอริทึมข้างต้น โดยเมธอด strtok() ของ string ถูกใช้เพื่อแยกสตริงและส่งคืนเป็นอาร์เรย์ลิสต์แบบ vector class
ตัวอย่าง
#include <cstring> #include <iostream> #include <vector> #include <string.h> // เมธอดสำหรับแยกสตริง std::vector<std::string> split(std::string str, std::string sep) { char* cstr = const_cast<char*>(str.c_str()); char* current; std::vector<std::string> arr; current = strtok(cstr, sep.c_str()); while (current != NULL) { arr.push_back(current); current = strtok(NULL, sep.c_str()); } return arr; } int main() { std::vector<std::string> word_list; std::cout << "string before replace::" << "Hello ajay yadav ! you ajay you are star" << std::endl; std::cout << "word to be replaced::" << "ajay" << std::endl; word_list = split("Hello ajay yadav ! you ajay you are star", " "); std::string result = ""; // สร้างเซ็นเซอร์เป็นข้อความดอกจัน "*" ตามความยาวของคำที่ต้องการเซ็นเซอร์ std::string stars = ""; std::string word = "ajay"; for (int i = 0; i < word.length(); i++) stars += '*'; // วนลูปผ่านรายการคำที่แยกออกมา int index = 0; for (std::string i : word_list) { if (i.compare(word) == 0) // เปลี่ยนคำที่ถูกเซ็นเซอร์เป็นดอกจันที่สร้างไว้ word_list[index] = stars; index++; } // รวมคำกลับเข้าด้วยกัน for (std::string i : word_list) { result += i + ' '; } std::cout << "output::" << result; return 0; }ตามที่เห็นในโค้ดข้างต้น โค้ดการดำเนินการสตริงทั้งหมดถูกรวมอยู่ในเมธอด retrieveChar() ซึ่งต่อมาถูกเรียกใช้ในฟังก์ชัน main()
ผลลัพธ์
String before replace::Hello ajay yadav ! you ajay you are star Word to be replaced::ajay Output::Hello **** yadav ! you **** you are star