
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
String Matching Using String Library in C++
Here we will see how the string library functions can be used to match strings in C++. Here we are using the find() operation to get the occurrences of the substring into the main string. This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches.
If the item is found, this function returns the position. But if it is not found, it will return string::npos.
Input: The main string “aabbabababbbaabb” and substring “abb” Output: The locations where the substrings are found. [1, 8, 13]
Algorithm
String_Find(main_str, sub_str)
Input − The main string and the substring to check
Output − The positions of the substring in the main string
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
Example Code
#include<iostream> 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; //new position is from next element of index } }
Output:
Match found at position: 1 Match found at position: 8 Match found at position: 13
Advertisements