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

โปรแกรม C++ จับคู่สตริงด้วย String Library


ที่นี่เราจะดูวิธีใช้ฟังก์ชันของ string library เพื่อจับคู่สตริงใน C++ เราใช้การดำเนินการ find() เพื่อหาตำแหน่งของสตริงย่อยในสตริงหลัก เมธอด find() นี้คืนค่าตำแหน่งแรกที่พบสตริง เราใช้ find() หลายครั้งเพื่อหาการจับคู่ทั้งหมด

ถ้าพบรายการ ฟังก์ชันจะคืนค่าตำแหน่ง แต่ถ้าไม่พบ จะคืนค่า string::npos

Input: สตริงหลัก "aabbabababbbaabb" และสตริงย่อย "abb"
Output: ตำแหน่งที่พบสตริงย่อย [1, 8, 13]

อัลกอริทึม

String_Find(main_str, sub_str)

Input: สตริงหลักและสตริงย่อยที่ต้องการตรวจสอบ

Output: ตำแหน่งของสตริงย่อยในสตริงหลัก

pos := 0
while index = first occurrence of sub_str into the str in range pos to end of the string, do
    print the index as there is a match
    pos := index + 1
done

ตัวอย่างโค้ด

#include <iostream>
#include <string>
using namespace std;

main() {
    string str1 = "aabbabababbbaabb";
    string str2 = "abb";
    int pos = 0;
    int index;
    
    while((index = str1.find(str2, pos)) != string::npos) {
        cout << "Match found at position: " << index << endl;
        pos = index + 1; // ตำแหน่งใหม่คือจากอีลีเมนต์ถัดไปของ index
    }
}

ผลลัพธ์:

Match found at position: 1
Match found at position: 8
Match found at position: 13