Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is ‘string.h’.
The substring function takes two values pos and len as an argument and returns a newly constructed string object with its value initialized to a copy of a sub-string of this object. Copying of string starts from pos and is done till pos+len means [pos, pos+len).
Syntax:
string substr (size_t pos, size_t len) const;
Parameters:
- pos: Position of the first character to be copied.
- len: Length of the sub-string.
- size_t: It is an unsigned integral type.
Return Value: It returns a string object.
Example:
C++
// C++ program to demonstrate functioning of substr() #include <iostream> #include <string.h> using namespace std; int main() { // Take any string string s1 = "Geeks" ; // Copy two characters of s1 (starting // from position 3) string r = s1.substr(3, 2); // prints the result cout << "String is: " << r; return 0; } |
String is: ks
- Time complexity: O(N)
- Auxiliary Space: O(N)
More examples:
string: “h e l l o w o r l d“
index: 0 1 2 3 4 5 6 7 8 9 10
if we write: – s.substr(s.begin(),3) => compilation error 🙂 (because cannnot convert a iterator to a int datatype )
s.substr(2,3) => llo (three letter from 2nd index)
s.substr(*s.begin()-s[0],3) => hel (s.begin() is ‘h’ then ‘h’-s[0]=> ‘h’-‘h’=0 means substr(0,3) —– three letter from zeroth index
s.substr(5,1) => ‘ ‘ (prints blank space , that is at 5th index)
s.substr(2,0) => (not output) (selects zero letters from second index)
Important Points to Remember
- The index of the first character is 0 (not 1).
- If pos is equal to the string length, the function returns an empty string.
- If pos is greater than the string length, it throws out_of_range. If this happens, there are no changes in the string.
- If the requested sub-string len is greater than the size of a string, then returned sub-string is [pos, size()).
- If len is not passed as a parameter, then returned sub-string is [pos, size()).
Applications of Substring
- Get a Sub-String after a character
- Get a Sub-String before a character
- Print all Sub-Strings of a given String
- Sum of all Substrings of a string representing a number
- Print the maximum value of all substrings of a string representing a number
- Print the minimum value of all substrings of a string representing a number
Get a Sub-String after a character
In this, a string and a character are given and you have to print the sub-string followed by the given character.
Extract everything after the “:” in the string “dog:cat“.
Example:
C++
// 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; } |
String is: cat
Time complexity: O(N)
Auxiliary Space: O(N)
How to Get a SubString before a character
In this, a string and a character are given and you have to print the sub-string followed by the given character.
Example:
C++
// 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 before pos // Extract everything before the ":" in the string // "dog:cat". string sub = s.substr(0, pos); // prints the result cout << "String is: " << sub; return 0; } |
String is: dog
Time complexity: O(N)
Auxiliary Space: O(N)
How to Print all Sub-Strings of a given String
Given a string as an input. We need to write a program that will print all non-empty substrings of that given string.
Example:
C++
// C++ program to demonstrate all possible // substrings of a given string #include <bits/stdc++.h> using namespace std; // Function to print all sub strings void subString(string s, int n) { // Pick starting point in 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 above function int main() { string s = "abcd" ; subString(s, s.length()); return 0; } |
a ab abc abcd b bc bcd c cd d
Time complexity: O( N3 )
Auxiliary Space: O(1)
Print Sum of all Substrings of a string representing a number
Given an integer represented as a string, we need to get the sum of all possible substrings of this string.
Example:
C++
// C++ program to print sum of all substring of // a number represented as a string #include <bits/stdc++.h> using namespace std; // Utility method to convert character digit to // integer digit int toDigit( char ch) { return (ch - '0' ); } // Returns sum of all substring of num int sumOfSubstrings(string num) { int n = num.length(); // allocate memory equal to length of string int sumofdigit[n]; // initialize first value with first digit sumofdigit[0] = toDigit(num[0]); int res = sumofdigit[0]; // loop over all digits of string for ( int i = 1; i < n; i++) { int numi = toDigit(num[i]); // update each sumofdigit from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value to the result res += sumofdigit[i]; } return res; } // Driver code to test above methods int main() { string num = "1234" ; cout << sumOfSubstrings(num) << endl; return 0; } |
1670
Time Complexity: O(N)
Auxiliary Space: O(N)
Print the maximum value of all substrings of a string representing a number
Given an integer represented as a string, we need to get the maximum of all possible substrings of the given string which is representing a number.
Example:
C++
// C++ program to demonstrate max. of all possible // substrings of a given string #include <bits/stdc++.h> using namespace std; void subString(string s, int n) { vector< int > v; for ( int i = 0; i < n; i++){ for ( int len = 1; len <= n - i; len++){ string sub =(s.substr(i, len)); int x=stoi(sub); v.push_back(x); } } cout<<*max_element(v.begin(),v.end())<<endl; } // Driver program to test above function int main() { string s = "823" ; subString(s, s.length()); return 0; } |
823
Explanation: All substrings are { 8, 82, 823, 2, 23, 3 } and the maximum value substring is 823.
Time complexity: O(N3)
Auxiliary space: O(N!)
Print the minimum value of all substrings of a string representing a number
Given an integer represented as a string, we need to get the minimum of all possible substrings of the given string which is representing a number.
Example:
C++
// C++ program to demonstrate minimum of all possible // substrings of a given string #include <bits/stdc++.h> using namespace std; void subString(string s, int n) { vector< int > v; for ( int i = 0; i < n; i++){ for ( int len = 1; len <= n - i; len++){ string sub =(s.substr(i, len)); int x=stoi(sub); v.push_back(x); } } cout<<*min_element(v.begin(),v.end())<<endl; } // Driver program to test above function int main() { string s = "4572" ; subString(s, s.length()); return 0; } |
2
Time complexity: O(N3)
Auxiliary space: O(N!)
Other Applications of Substring
- Text Searching: Substrings are used to search for words or phrases in larger bodies of text. This is commonly used in search engines, where a user might type in a phrase or keyword and the engine will search for any matches containing that substring.
- Text Parsing: Substrings are used in text parsing algorithms to break down larger strings into smaller chunks. For example, a parser might be used to extract individual words from a sentence and store them in a data structure.
- Text Manipulation: Substrings are used in text manipulation applications to find and replace certain words or phrases in larger bodies of text. This can be used to perform search and replace tasks, or to update information in a document.
- Natural Language Processing: Substrings are used in natural language processing algorithms to identify words and phrases. This is used in applications such as speech recognition, where the algorithm must identify words spoken by a user.
- Pattern Recognition: Substrings are used in pattern recognition algorithms to identify patterns in data. This can be used to identify trends in financial data, or to detect anomalies in images.
- Password Security: Substrings are used to verify passwords. This is done by comparing the entered password against a stored substring of the original password. If the two match, then the password is verified. This technique is used in many applications to increase security.
Please Login to comment...