The C++ string class uses a char array to store characters, but the string class handles all memory management, allocation, and null termination, which is why it is so simple to use. Because of dynamic memory allocation, similar to vectors, the length of a C++ string can be modified at runtime.

Since the string class is a container class, you can use an iterator to iterate over all of its characters, much as you can for other containers like vectors, sets, and maps. However, you usually use a simple for loop to iterate over the characters and index them with the [] operator.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Substring

In C++, a part of a string is referred to as a substring. substr is a C++ function for obtaining a substring (). There are two parameters in this function: pos and len. The pos parameter defines the substring's start location, while the len indicates the number of characters in the substring.

  • The first character's index is 0 (not 1).
  • The function returns an empty string if pos is equal to the length of the string.
  • It throws out of range if pos is longer than the string length. There are no modifications in the string if this happens.
  • If the length of the requested sub-string is greater than the length of the string, the sub-string is returned as [pos, size()).

Basic Syntax: 

std::stringsubstr(size_tpos, size_tlen) const;

Pos-> represents starting index of the substring

Len-> represents length of the substring

Example:

#include <string.h>

#include <iostream>

using namespace std; 

int main()

{

         // Take any string

         string s1 = "Welcome"; 

         // Copy three characters of s1 (starting

         // from position 1)

         string r = s1.substr(1, 3);

         // prints the result

         cout<< "String is: " << r;

 

         return 0;

}

Output:

CppSubstring_1.

Explanation:

In the above example, it is mandatory to include the string header file because substring is also one of the string functions. The input string is represented by the variable- s1. The output string is represented by variable r. The output string variable executes the C++ substring function and prints the output value. In substr(1,3), the first argument indicates the starting position. Generally the index starts from 0 therefore the first argument 1 is the second character of the string. Second argument 3 indicates the length of the string. Thus the result will be  3 characters from the input string starting from the second character which is “elc”.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Sample Code:

#include <iostream>

#include <string.h>

using namespace std;

int main() {

string a = "Hello welcome you all ";

string b = a.substr(11, 3);

string c = a.substr(0, 6);

cout<< "Substring starting at position 11 and length 3 is: " << b <<endl;

cout<< "Substring starting at position 0 and length 6 is: " << c;

return 0;

Output:

CppSubstring_2.

In the above program, the first string variable a is declared as “Hello welcome you all”. Then the second string b stores the substring which start from the 11th position and the length becomes 3. So, the resultant value of b becomes “me”. Next, the string c stores the substring which starts from 0 and the length becomes 6, and the resultant value of c becomes “Hello”.

Sample code:

#include <string>

#include <iostream>

int main()

{

std::string a = "abcdefghijklmnopqrstuvwxyz";

// count is npos, returns [pos, size())

std::string s1 = a.substr(10);

std::cout<< s1 << '\n';

// both pos and pos+count are within bounds, returns [pos, pos+count)

std::string s2 = a.substr(5, 3);

std::cout<< s2 << '\n';

// pos is within bounds, pos+count is not, returns [pos, size())

std::string s4 = a.substr(a.size()-3, 50);

// this is effectively equivalent to

// std::string sub4 = a.substr(17, 3);

// since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3

std::cout<< s4 << '\n'; 

try {

     // pos is out of bounds, throws

std::string sub5 = a.substr(a.size()+3, 50);

std::cout<< sub5 << '\n';

} catch(conststd::out_of_range& e) {

std::cout<< "pos exceeds string size\n";

}

}

Output:

CppSubstring_3 

Explanation:

In the above example, the input string variable ‘a’  is “abcdefghijklmnopqrstuvwxyz”. s1,s2,s4 are output string variables. 

 S1 variable holds the output of substr(10) returns string starting from the 10th position as “klmnopqrstuvwxyz”. 

S2 variable holds the output of substr(5,3) returns string starting from the 5th position and number of characters as 3 results “fgh”.

S3 variable holds the output of substr(a.size()-3,50) returns string as xyz.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Pattern Matching Using C++ Substring

#include<iostream>

#include<cstdlib>

using namespace std;

int main()

{

inti,j,temp;

charstr[100]={"Welcome you all to the learning team"};

charsubstr[20]={"Welcome"};

for(i=0;str[i]!='\0';i++)

{

     j=0;

if(str[i]==substr[j])

     {

temp=i+1;

while(str[i]==substr[j])

         {

i++;

j++;

         }

if(substr[j]=='\0')

         {

cout<<"The substring is present in given string at position "<<temp<<"\n";

exit(0);

         }

else

         {

i=temp;

temp=0;

         }

     }

}

if(temp==0)

cout<<"The substring is not present in given string\n"; 

return 0;

}

Output:

CppSubstring_4.

Explanation:

The above example represents the pattern matching scenario. It checks if the given pattern of the string presented in the main string is the input string or not. If it is present, it will return the substring that is present in the given string along with the position. If not, it will return if the given substring is not present.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In C++, a substring is a segment of a string, and you use the substr() function to extract a substring from a specified string. This substr() function extracts a substring from a string beginning at the specified position and going up to the length specified in characters from the starting position.

The above information will give a detailed explanation of what is substring in C++, basic syntax, basic example, C++ substring example with starting position and length, pattern matching.

In this article, you learned about stack, implementation, operations with syntax, and examples. To get expertise in C++ programming you can join our Simplilearn's Full Stack Web Development course. For learners, Simplilearn has made a special selection of courses available for free. Join Simplilearn for free Simplilearns free courses and revolutionize your profession with certificates, specializations, and dozens of other courses.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors