Find substring in C++
Substring in C++:
The substring function handles string operations like strcat(), append(), etc. It creates a brand-new string and sets its value to a duplicate of a substring of this object.
'string.h' is a header file needed in C++ for the string functions std::substr() and std::str().
The substring function accepts the values pos and len as arguments and produces a freshly created string object with its value set to a duplicate of a sub-string of the original object. A string is copied from pos and continues until pos+len means [pos, pos+len].
Syntax for substr:
string substr (size_t pos, size_t len) const;
Parameters in Function:
Pos indicates the first character that will be duplicated.
Len: The sub-string's length.
Program
// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
// Take any string
string s1 = "Geeks";
string r = s1.substr(3, 2);
// print result
cout << "String is: " << r;
return 0;
}
Output:
![Find substring in C++](https://static.tutorialandexample.com/cpp/find-substring-in-cpp1.png)
Time complexity: O(N)
Auxiliary Space: O(N)
More instances:
- "myatricle" is a string.
- Index: 0 1 2 3 4 5 6 7 8 9.
If we enter the following code: -
s.substr(s.begin(),3) => compilation error (since an iterator cannot be converted to an int datatype)
s.substr(2,3) => llo (Two letters from the second index)
s.substr(*s.begin()-s[0],3) = > if s.begin() returns 'h', then 'h'-s[0]=> "h"-"h"=0 denotes substr(0,3). — three letters from index zero
s.substr(5,1) =>'' (prints a blank space at the fifth index)
s.substr(2,0) =>(not a result) (Picks 0 letters from 2nd index)
Points to Remember:
- The initial character's index is 0 (not 1), not 1.
- The function returns an empty string if pos is equal to the length of the string.
- It throws out_of_range if the position is more significant than the length of the string. If this occurs, the string remains unchanged.
- The returned sub-string is [pos, size()] if the requested sub-string len is more than the length of a string.
- If len is not provided as a parameter, [pos, size()] is returned as the sub-string.
The Uses of Substrings:-
- Obtain a Sub-String following a character.
- Before a character, obtain a Sub-String.
- Print every Sub-String of the specified String.
- the sum of each substring in a string that is used to represent a number
- Print out the string representing a number's longest substring up to its maximum value.
- Print out the string expressing a number's minimal value across all its substrings.
Obtain a Sub-String following a character:
- You must print the sub-string followed by the provided character after being given a string and a character in this exercise.
- Remove everything from the string "dog:cat" that comes after the ":".
// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
// Take any string
string s = "dog:cat";
// Find position of ':' using find()
int pos = s.find(":");
// Copy substring after pos
string sub = s.substr(pos + 1);
// prints the result
cout << "String is: " << sub;
return 0;
}
Output:
![Find substring in C++](https://static.tutorialandexample.com/cpp/find-substring-in-cpp2.png)
Time complexity: O(N)
Auxiliary Space: O(N)
Get a SubString before a character:
You must print the sub-string followed by the provided character after being given a string and a character in this exercise.
// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
// Take any string
string s = "dog:cat";
int pos = s.find(":");
// Extract everything before the ":" in the string
// "dog:cat".
string sub = s.substr(0, pos);
// prints the result
cout << "String is: " << sub;
return 0;
}
Output:
![Find substring in C++](https://static.tutorialandexample.com/cpp/find-substring-in-cpp3.png)
Time complexity: O(N)
Auxiliary Space: O(N)
How to print every substring contained in a given string:-
A string is provided as input. A program must be written to print every non-empty substring of the given string.
// C++ program to demonstrate all possible
// substrings of a given string
#include <bits/stdc++.h>
using namespace std;
//function to print all substrings
void subString(string s, int n)
{
// Pick starting point in the outer loop
// and lengths of different strings for
// a given starting point
for (int i = 0; i < n; i++)
for (int len = 1; len <= n - i; len++)
cout << s.substr(i, len) << endl;
}
// Driver program to test the above function
int main()
{
string s = "abcd";
substring(s, s.length());
return 0;
}
Output:
![Find substring in C++](https://static.tutorialandexample.com/cpp/find-substring-in-cpp4.png)
Time complexity: O( N3 )
Auxiliary Space: O(1)
Other uses for Substring in C++:
- Text searching: Text searching includes looking for certain words or phrases in longer volumes of text. When a user enters a phrase or keyword into a search engine, the system will look for matches containing that substring.
- Text Parsing: Text parsing algorithms use substrings to split longer strings into manageable pieces. For instance, a parser could be used to separate the words from a sentence and put them in a data structure.
- Text Manipulation: Text manipulation programs use substrings to search for and replace specific words or phrases within longer passages of text. This can be used to update document data or execute search and replace operations.
- Natural Language Processing: Substrings are employed by algorithms for natural language processing to recognize words and phrases. This is applied in programs like speech recognition, where the algorithm needs to recognize user-spoken words.
- Pattern Recognition: Substrings are tool pattern recognition algorithms use to find patterns in data. This can be used to find patterns in financial data or spot irregularities in pictures.
- Pattern Security: Substrings are used to check passwords in terms of password security. This is accomplished by comparing the entered password to a substring of the original password that has been kept. The password is confirmed if the two are identical. Many programs use this method to boost security.