Algorithm na bincike na kirtani (String Search) a C++- Bayani, Misali da Lamba

Ana amfani da algorithm ɗin bincike na kirtani don nemo abubuwan da suka faru na ƙayyadaddun tsari(substring) a cikin babban rubutu(kirtani). Wannan algorithm yana taka muhimmiyar rawa wajen sarrafa rubutu, bincike, da ayyukan magudi.

Yadda Ake Aiki

  1. Fara da rubutu(kirtani) da tsari(ƙarshen igiya) don nema.
  2. Maimaita ta cikin rubutun harafi ɗaya a lokaci guda.
  3. Ga kowane harafi a cikin rubutun, kwatanta shi da harafin farko na ƙirar.
  4. Idan akwai wasa, duba idan haruffan da ke gaba kuma sun dace da tsarin.
  5. Idan tsarin ya dace sosai, yi rikodin matsayin farawa na wasan.
  6. Ci gaba da neman tsari a cikin rubutun.

Misali

Yi la'akari da rubutu: "ababcababcabcabc" Kuma tsari: "abc"

  1. Fara a matsayi 0. Kwatanta "a" tare da harafin farko "a" a cikin tsari.
  2. An samo daidai, matsa zuwa haruffa na gaba: "b" tare da "b", da "a" tare da "c".
  3. Ci gaba da daidaitawa: "b" tare da "a", "a" tare da "b", da "b" tare da "c".
  4. Wasan ya gaza a matsayi na 2.
  5. Fara sake a matsayi na 3. Kwatanta "a" tare da harafin farko "a" a cikin tsari.
  6. Wasan nasara: "a" tare da "a", "b" tare da "b", da "c" tare da "c".
  7. Matsayin rikodin 3.

Ana samun samfurin "abc" a matsayi na 0, 6, da 9.

Misali Code a C++

#include <iostream>  
#include <string>  
#include <vector>  
  
std::vector<int> stringSearch(const std::string& text, const std::string& pattern) {  
    std::vector<int> positions;  
  
    for(int i = 0; i <= text.length()- pattern.length(); ++i) {  
        int j = 0;  
        while(j < pattern.length() && text[i + j] == pattern[j]) {  
            ++j;  
        }  
        if(j == pattern.length()) {  
            positions.push_back(i);  
        }  
    }  
  
    return positions;  
}  
  
int main() {  
    std::string text = "ababcababcabcabc";  
    std::string pattern = "abc";  
  
    std::vector<int> result = stringSearch(text, pattern);  
  
    std::cout << "Pattern found at positions: ";  
    for(int pos: result) {  
        std::cout << pos << ";  
    }  
    std::cout << std::endl;  
  
    return 0;  
}  

A cikin wannan misali, stringSearch ana amfani da aikin don nemo abubuwan da suka faru na tsarin "abc" a cikin rubutun "ababcababcabcabc". Sakamakon zai zama vector mai kunshe da wuraren farawa na matches.