- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a string contains a sub-string 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.
So for checking whether the substring is present into the main string, we have to check the return value of find() is string::npos or not.
Here we are simply getting the position where the substring is present.
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 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
- Related Articles
- How to check if a string contains a specific sub string?
- Check if a string contains a palindromic sub-string of even length in C++
- Method to check if a String contains a sub string ignoring case in Java
- Check if a string contains a palindromic sub-string of even length in Python
- Check if a string can become empty by recursively deleting a given sub-string in C++
- Check if a string contains numbers in MySQL?
- Check if a field contains a string in MongoDB?
- Check if string contains another string in Swift
- How to check if a string contains a certain word in C#?
- Check if a string contains a number using Java.
- C# program to check if a string contains any special character
- Check if a binary string contains consecutive same or not in C++
- Program to check if a string contains any special character in C
- Check if a string can become empty by recursively deleting a given sub-string in Python
- MySQL query to check if a string contains a word?
