เป็นโปรแกรม C++ สำหรับค้นหาข้อความเดิมซ้ำๆ
อัลกอริทึม
Begin Take the original string and pattern to be searched as input. org_len = store the length of original string pat_len = store the length of pattern for i = 0 to (org_len - pat_len) for j = 0 to pat_len - 1 if (org[i + j] != patt[j]) if (j == pat_len) Increase m. Print the position at which the pattern is found if (m == 0) Print no match found else Print the total number of instances found. return 0 End
ตัวอย่าง
#include<iostream> #include<string.h> using namespace std; int main() { char org[150], patt[150]; int i, j, m = 0, org_len, pat_len; cout << "\nEnter Original String:"; cin >> org; cout << "Enter Pattern to Search:"; cin >> patt; org_len = strlen(org); //store the length of original string pat_len = strlen(patt); //store the length of pattern for (i = 0; i <= (org_len - pat_len); i++) { for (j = 0; j < pat_len; j++) { if (org[i + j] != patt[j]) break; } if (j == pat_len) { m++; cout << "\nPattern Found at Position: " << i; } } if (m == 0) cout << "\nNo Match Found."; else cout << "\nTotal Number of Instances Found = " << m; return 0; }
ผลลัพธ์
Enter Original String:thisistutorialspoint.thisisac++program Enter Pattern to Search:is Pattern Found at Position: 2 Pattern Found at Position: 4 Pattern Found at Position: 23 Pattern Found at Position: 25 Total Number of Instances Found = 4